blob: 18eac4c7f968b4ac05785885d24ef2bcecf10a12 [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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Value.h"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000031#include "llvm/Support/BlockFrequency.h"
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +000032#include "llvm/Support/CommandLine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000039#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000040#include <cmath>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000041#include <limits>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000042using namespace llvm;
43
Devang Patel19974732007-05-03 01:11:54 +000044char LiveIntervals::ID = 0;
Jakob Stoklund Olesendcc44362012-08-03 22:12:54 +000045char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +000046INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
47 "Live Interval Analysis", false, false)
Andrew Trick8dd26252012-02-10 04:10:36 +000048INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Owen Anderson2ab36d32010-10-12 19:48:12 +000049INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Andrew Trick8dd26252012-02-10 04:10:36 +000050INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson2ab36d32010-10-12 19:48:12 +000051INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson2ab36d32010-10-12 19:48:12 +000052INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersonce665bd2010-10-07 22:25:06 +000053 "Live Interval Analysis", false, false)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000054
Chris Lattnerf7da2c72006-08-24 22:43:55 +000055void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000056 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000057 AU.addRequired<AliasAnalysis>();
58 AU.addPreserved<AliasAnalysis>();
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +000059 // LiveVariables isn't really required by this analysis, it is only required
60 // here to make sure it is live during TwoAddressInstructionPass and
61 // PHIElimination. This is temporary.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 AU.addRequired<LiveVariables>();
Evan Cheng148341c2010-08-17 21:00:37 +000063 AU.addPreserved<LiveVariables>();
Andrew Trickd35576b2012-02-13 20:44:42 +000064 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +000065 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling67d65bb2008-01-04 20:54:55 +000066 AU.addPreservedID(MachineDominatorsID);
Lang Hames233a60e2009-11-03 23:52:08 +000067 AU.addPreserved<SlotIndexes>();
68 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000070}
71
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000072LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
73 DomTree(0), LRCalc(0) {
74 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
75}
76
77LiveIntervals::~LiveIntervals() {
78 delete LRCalc;
79}
80
Chris Lattnerf7da2c72006-08-24 22:43:55 +000081void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000082 // Free the live intervals themselves.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +000083 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
84 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
85 VirtRegIntervals.clear();
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +000086 RegMaskSlots.clear();
87 RegMaskBits.clear();
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +000088 RegMaskBlocks.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000089
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000090 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
91 delete RegUnitIntervals[i];
92 RegUnitIntervals.clear();
93
Benjamin Kramerce9a20b2010-06-26 11:30:59 +000094 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
95 VNInfoAllocator.Reset();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000096}
97
Owen Anderson80b3ce62008-05-28 20:54:50 +000098/// runOnMachineFunction - Register allocate the whole function
99///
100bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000101 MF = &fn;
102 MRI = &MF->getRegInfo();
103 TM = &fn.getTarget();
104 TRI = TM->getRegisterInfo();
105 TII = TM->getInstrInfo();
106 AA = &getAnalysis<AliasAnalysis>();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000107 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000108 DomTree = &getAnalysis<MachineDominatorTree>();
109 if (!LRCalc)
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000110 LRCalc = new LiveRangeCalc();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000111
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000112 // Allocate space for all virtual registers.
113 VirtRegIntervals.resize(MRI->getNumVirtRegs());
114
Jakob Stoklund Olesenec7b25d2013-02-09 00:04:07 +0000115 computeVirtRegs();
116 computeRegMasks();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000117 computeLiveInRegUnits();
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000118
Chris Lattner70ca3582004-09-30 15:59:17 +0000119 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000120 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000121}
122
Chris Lattner70ca3582004-09-30 15:59:17 +0000123/// print - Implement the dump method.
Chris Lattner45cfe542009-08-23 06:03:38 +0000124void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000125 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000126
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000127 // Dump the regunits.
128 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
129 if (LiveInterval *LI = RegUnitIntervals[i])
130 OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
131
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000132 // Dump the virtregs.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +0000133 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
134 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
135 if (hasInterval(Reg))
136 OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
137 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000138
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000139 OS << "RegMasks:";
140 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
141 OS << ' ' << RegMaskSlots[i];
142 OS << '\n';
143
Evan Cheng752195e2009-09-14 21:33:42 +0000144 printInstrs(OS);
145}
146
147void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000148 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000149 MF->print(OS, Indexes);
Chris Lattner70ca3582004-09-30 15:59:17 +0000150}
151
Manman Renb720be62012-09-11 22:23:19 +0000152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng752195e2009-09-14 21:33:42 +0000153void LiveIntervals::dumpInstrs() const {
David Greene8a342292010-01-04 22:49:02 +0000154 printInstrs(dbgs());
Evan Cheng752195e2009-09-14 21:33:42 +0000155}
Manman Ren77e300e2012-09-06 19:06:06 +0000156#endif
Evan Cheng752195e2009-09-14 21:33:42 +0000157
Owen Anderson03857b22008-08-13 21:49:13 +0000158LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000159 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000160 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000161}
Evan Chengf2fbca62007-11-12 06:35:08 +0000162
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000163
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000164/// computeVirtRegInterval - Compute the live interval of a virtual register,
165/// based on defs and uses.
166void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
167 assert(LRCalc && "LRCalc not initialized.");
168 assert(LI->empty() && "Should only compute empty intervals.");
169 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
170 LRCalc->createDeadDefs(LI);
171 LRCalc->extendToUses(LI);
172}
173
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000174void LiveIntervals::computeVirtRegs() {
175 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
176 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
177 if (MRI->reg_nodbg_empty(Reg))
178 continue;
179 LiveInterval *LI = createInterval(Reg);
180 VirtRegIntervals[Reg] = LI;
181 computeVirtRegInterval(LI);
182 }
183}
184
185void LiveIntervals::computeRegMasks() {
186 RegMaskBlocks.resize(MF->getNumBlockIDs());
187
188 // Find all instructions with regmask operands.
189 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
190 MBBI != E; ++MBBI) {
191 MachineBasicBlock *MBB = MBBI;
192 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
193 RMB.first = RegMaskSlots.size();
194 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
195 MI != ME; ++MI)
196 for (MIOperands MO(MI); MO.isValid(); ++MO) {
197 if (!MO->isRegMask())
198 continue;
199 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
200 RegMaskBits.push_back(MO->getRegMask());
201 }
202 // Compute the number of register mask instructions in this block.
Dmitri Gribenko2de05722012-09-10 21:26:47 +0000203 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000204 }
205}
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000206
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000207//===----------------------------------------------------------------------===//
208// Register Unit Liveness
209//===----------------------------------------------------------------------===//
210//
211// Fixed interference typically comes from ABI boundaries: Function arguments
212// and return values are passed in fixed registers, and so are exception
213// pointers entering landing pads. Certain instructions require values to be
214// present in specific registers. That is also represented through fixed
215// interference.
216//
217
218/// computeRegUnitInterval - Compute the live interval of a register unit, based
219/// on the uses and defs of aliasing registers. The interval should be empty,
220/// or contain only dead phi-defs from ABI blocks.
221void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
222 unsigned Unit = LI->reg;
223
224 assert(LRCalc && "LRCalc not initialized.");
225 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
226
227 // The physregs aliasing Unit are the roots and their super-registers.
228 // Create all values as dead defs before extending to uses. Note that roots
229 // may share super-registers. That's OK because createDeadDefs() is
230 // idempotent. It is very rare for a register unit to have multiple roots, so
231 // uniquing super-registers is probably not worthwhile.
232 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosierb018bab2013-05-22 22:36:55 +0000233 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
234 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000235 if (!MRI->reg_empty(*Supers))
236 LRCalc->createDeadDefs(LI, *Supers);
237 }
238 }
239
240 // Now extend LI to reach all uses.
241 // Ignore uses of reserved registers. We only track defs of those.
242 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosierb018bab2013-05-22 22:36:55 +0000243 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
244 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000245 unsigned Reg = *Supers;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000246 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000247 LRCalc->extendToUses(LI, Reg);
248 }
249 }
250}
251
252
253/// computeLiveInRegUnits - Precompute the live ranges of any register units
254/// that are live-in to an ABI block somewhere. Register values can appear
255/// without a corresponding def when entering the entry block or a landing pad.
256///
257void LiveIntervals::computeLiveInRegUnits() {
258 RegUnitIntervals.resize(TRI->getNumRegUnits());
259 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
260
261 // Keep track of the intervals allocated.
262 SmallVector<LiveInterval*, 8> NewIntvs;
263
264 // Check all basic blocks for live-ins.
265 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
266 MFI != MFE; ++MFI) {
267 const MachineBasicBlock *MBB = MFI;
268
269 // We only care about ABI blocks: Entry + landing pads.
270 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
271 continue;
272
273 // Create phi-defs at Begin for all live-in registers.
274 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
275 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
276 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
277 LIE = MBB->livein_end(); LII != LIE; ++LII) {
278 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
279 unsigned Unit = *Units;
280 LiveInterval *Intv = RegUnitIntervals[Unit];
281 if (!Intv) {
282 Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
283 NewIntvs.push_back(Intv);
284 }
285 VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay05b46f02012-06-05 23:00:03 +0000286 (void)VNI;
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000287 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
288 }
289 }
290 DEBUG(dbgs() << '\n');
291 }
292 DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
293
294 // Compute the 'normal' part of the intervals.
295 for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
296 computeRegUnitInterval(NewIntvs[i]);
297}
298
299
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000300/// shrinkToUses - After removing some uses of a register, shrink its live
301/// range to just the remaining uses. This method does not compute reaching
302/// defs for new uses, and it doesn't remove dead defs.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000303bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000304 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000305 DEBUG(dbgs() << "Shrink: " << *li << '\n');
306 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hames567cdba2012-01-03 20:05:57 +0000307 && "Can only shrink virtual registers");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000308 // Find all the values used, including PHI kills.
309 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
310
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000311 // Blocks that have already been added to WorkList as live-out.
312 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
313
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000314 // Visit all instructions reading li->reg.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000315 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000316 MachineInstr *UseMI = I.skipInstruction();) {
317 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
318 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000319 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000320 LiveRangeQuery LRQ(*li, Idx);
321 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesen9ef931e2011-03-18 03:06:04 +0000322 if (!VNI) {
323 // This shouldn't happen: readsVirtualRegister returns true, but there is
324 // no live value. It is likely caused by a target getting <undef> flags
325 // wrong.
326 DEBUG(dbgs() << Idx << '\t' << *UseMI
327 << "Warning: Instr claims to read non-existent value in "
328 << *li << '\n');
329 continue;
330 }
Jakob Stoklund Olesenf054e192011-11-14 18:45:38 +0000331 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000332 // register one slot early.
333 if (VNInfo *DefVNI = LRQ.valueDefined())
334 Idx = DefVNI->def;
335
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000336 WorkList.push_back(std::make_pair(Idx, VNI));
337 }
338
339 // Create a new live interval with only minimal live segments per def.
340 LiveInterval NewLI(li->reg, 0);
341 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
342 I != E; ++I) {
343 VNInfo *VNI = *I;
344 if (VNI->isUnused())
345 continue;
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000346 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000347 }
348
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000349 // Keep track of the PHIs that are in use.
350 SmallPtrSet<VNInfo*, 8> UsedPHIs;
351
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000352 // Extend intervals to reach all uses in WorkList.
353 while (!WorkList.empty()) {
354 SlotIndex Idx = WorkList.back().first;
355 VNInfo *VNI = WorkList.back().second;
356 WorkList.pop_back();
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000357 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000358 SlotIndex BlockStart = getMBBStartIdx(MBB);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000359
360 // Extend the live range for VNI to be live at Idx.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000361 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
Nick Lewycky4b11a702011-03-02 01:43:30 +0000362 (void)ExtVNI;
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000363 assert(ExtVNI == VNI && "Unexpected existing value number");
364 // Is this a PHIDef we haven't seen before?
Jakob Stoklund Olesenc29d9b32011-03-03 00:20:51 +0000365 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000366 continue;
367 // The PHI is live, make sure the predecessors are live-out.
368 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
369 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000370 if (!LiveOut.insert(*PI))
371 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000372 SlotIndex Stop = getMBBEndIdx(*PI);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000373 // A predecessor is not required to have a live-out value for a PHI.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000374 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000375 WorkList.push_back(std::make_pair(Stop, PVNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000376 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000377 continue;
378 }
379
380 // VNI is live-in to MBB.
381 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000382 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000383
384 // Make sure VNI is live-out from the predecessors.
385 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
386 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000387 if (!LiveOut.insert(*PI))
388 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000389 SlotIndex Stop = getMBBEndIdx(*PI);
390 assert(li->getVNInfoBefore(Stop) == VNI &&
391 "Wrong value out of predecessor");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000392 WorkList.push_back(std::make_pair(Stop, VNI));
393 }
394 }
395
396 // Handle dead values.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000397 bool CanSeparate = false;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000398 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
399 I != E; ++I) {
400 VNInfo *VNI = *I;
401 if (VNI->isUnused())
402 continue;
403 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
404 assert(LII != NewLI.end() && "Missing live range for PHI");
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000405 if (LII->end != VNI->def.getDeadSlot())
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000406 continue;
Jakob Stoklund Olesena4d34732011-03-02 00:33:01 +0000407 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000408 // This is a dead PHI. Remove it.
Jakob Stoklund Olesenb2beac22012-08-03 20:59:32 +0000409 VNI->markUnused();
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000410 NewLI.removeRange(*LII);
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000411 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
412 CanSeparate = true;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000413 } else {
414 // This is a dead def. Make sure the instruction knows.
415 MachineInstr *MI = getInstructionFromIndex(VNI->def);
416 assert(MI && "No instruction defining live value");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000417 MI->addRegisterDead(li->reg, TRI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000418 if (dead && MI->allDefsAreDead()) {
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000419 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000420 dead->push_back(MI);
421 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000422 }
423 }
424
425 // Move the trimmed ranges back.
426 li->ranges.swap(NewLI.ranges);
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000427 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000428 return CanSeparate;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000429}
430
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000431void LiveIntervals::extendToIndices(LiveInterval *LI,
432 ArrayRef<SlotIndex> Indices) {
433 assert(LRCalc && "LRCalc not initialized.");
434 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
435 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
436 LRCalc->extend(LI, Indices[i]);
437}
438
439void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
440 SmallVectorImpl<SlotIndex> *EndPoints) {
441 LiveRangeQuery LRQ(*LI, Kill);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000442 VNInfo *VNI = LRQ.valueOut();
443 if (!VNI)
444 return;
445
446 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
447 SlotIndex MBBStart, MBBEnd;
448 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
449
450 // If VNI isn't live out from KillMBB, the value is trivially pruned.
451 if (LRQ.endPoint() < MBBEnd) {
452 LI->removeRange(Kill, LRQ.endPoint());
453 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
454 return;
455 }
456
457 // VNI is live out of KillMBB.
458 LI->removeRange(Kill, MBBEnd);
459 if (EndPoints) EndPoints->push_back(MBBEnd);
460
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000461 // Find all blocks that are reachable from KillMBB without leaving VNI's live
462 // range. It is possible that KillMBB itself is reachable, so start a DFS
463 // from each successor.
464 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
465 VisitedTy Visited;
466 for (MachineBasicBlock::succ_iterator
467 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
468 SuccI != SuccE; ++SuccI) {
469 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
470 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
471 I != E;) {
472 MachineBasicBlock *MBB = *I;
473
474 // Check if VNI is live in to MBB.
475 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
476 LiveRangeQuery LRQ(*LI, MBBStart);
477 if (LRQ.valueIn() != VNI) {
478 // This block isn't part of the VNI live range. Prune the search.
479 I.skipChildren();
480 continue;
481 }
482
483 // Prune the search if VNI is killed in MBB.
484 if (LRQ.endPoint() < MBBEnd) {
485 LI->removeRange(MBBStart, LRQ.endPoint());
486 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
487 I.skipChildren();
488 continue;
489 }
490
491 // VNI is live through MBB.
492 LI->removeRange(MBBStart, MBBEnd);
493 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000494 ++I;
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000495 }
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000496 }
497}
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000498
Evan Chengf2fbca62007-11-12 06:35:08 +0000499//===----------------------------------------------------------------------===//
500// Register allocator hooks.
501//
502
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000503void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
504 // Keep track of regunit ranges.
505 SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
506
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000507 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
508 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000509 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000510 continue;
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000511 LiveInterval *LI = &getInterval(Reg);
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000512 if (LI->empty())
513 continue;
514
515 // Find the regunit intervals for the assigned register. They may overlap
516 // the virtual register live range, cancelling any kills.
517 RU.clear();
518 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
519 ++Units) {
520 LiveInterval *RUInt = &getRegUnit(*Units);
521 if (RUInt->empty())
522 continue;
523 RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
524 }
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000525
526 // Every instruction that kills Reg corresponds to a live range end point.
527 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
528 ++RI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000529 // A block index indicates an MBB edge.
530 if (RI->end.isBlock())
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000531 continue;
532 MachineInstr *MI = getInstructionFromIndex(RI->end);
533 if (!MI)
534 continue;
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000535
536 // Check if any of the reguints are live beyond the end of RI. That could
537 // happen when a physreg is defined as a copy of a virtreg:
538 //
539 // %EAX = COPY %vreg5
540 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
541 // BAR %EAX<kill>
542 //
543 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
544 bool CancelKill = false;
545 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
546 LiveInterval *RInt = RU[u].first;
547 LiveInterval::iterator &I = RU[u].second;
548 if (I == RInt->end())
549 continue;
550 I = RInt->advanceTo(I, RI->end);
551 if (I == RInt->end() || I->start >= RI->end)
552 continue;
553 // I is overlapping RI.
554 CancelKill = true;
555 break;
556 }
557 if (CancelKill)
558 MI->clearRegisterKills(Reg, NULL);
559 else
560 MI->addRegisterKilled(Reg, NULL);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000561 }
562 }
563}
564
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000565MachineBasicBlock*
566LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
567 // A local live range must be fully contained inside the block, meaning it is
568 // defined and killed at instructions, not at block boundaries. It is not
569 // live in or or out of any block.
570 //
571 // It is technically possible to have a PHI-defined live range identical to a
572 // single block, but we are going to return false in that case.
Lang Hames233a60e2009-11-03 23:52:08 +0000573
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000574 SlotIndex Start = LI.beginIndex();
575 if (Start.isBlock())
576 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000577
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000578 SlotIndex Stop = LI.endIndex();
579 if (Stop.isBlock())
580 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000581
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000582 // getMBBFromIndex doesn't need to search the MBB table when both indexes
583 // belong to proper instructions.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000584 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
585 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000586 return MBB1 == MBB2 ? MBB1 : NULL;
Evan Cheng81a03822007-11-17 00:40:40 +0000587}
588
Jakob Stoklund Olesen0ab71032012-08-03 20:10:24 +0000589bool
590LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
591 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
592 I != E; ++I) {
593 const VNInfo *PHI = *I;
594 if (PHI->isUnused() || !PHI->isPHIDef())
595 continue;
596 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
597 // Conservatively return true instead of scanning huge predecessor lists.
598 if (PHIMBB->pred_size() > 100)
599 return true;
600 for (MachineBasicBlock::const_pred_iterator
601 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
602 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
603 return true;
604 }
605 return false;
606}
607
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000608float
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000609LiveIntervals::getSpillWeight(bool isDef, bool isUse, BlockFrequency freq) {
610 const float Scale = 1.0f / BlockFrequency::getEntryFrequency();
611 return (isDef + isUse) * (freq.getFrequency() * Scale);
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000612}
613
Owen Andersonc4dc1322008-06-05 17:15:43 +0000614LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesffd13262009-07-09 03:57:02 +0000615 MachineInstr* startInst) {
Owen Andersonc4dc1322008-06-05 17:15:43 +0000616 LiveInterval& Interval = getOrCreateInterval(reg);
617 VNInfo* VN = Interval.getNextValue(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000618 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000619 getVNInfoAllocator());
Lang Hames86511252009-09-04 20:41:11 +0000620 LiveRange LR(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000621 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Lang Hames74ab5ee2009-12-22 00:11:50 +0000622 getMBBEndIdx(startInst->getParent()), VN);
Owen Andersonc4dc1322008-06-05 17:15:43 +0000623 Interval.addRange(LR);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000624
Owen Andersonc4dc1322008-06-05 17:15:43 +0000625 return LR;
626}
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000627
628
629//===----------------------------------------------------------------------===//
630// Register mask functions
631//===----------------------------------------------------------------------===//
632
633bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
634 BitVector &UsableRegs) {
635 if (LI.empty())
636 return false;
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000637 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
638
639 // Use a smaller arrays for local live ranges.
640 ArrayRef<SlotIndex> Slots;
641 ArrayRef<const uint32_t*> Bits;
642 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
643 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
644 Bits = getRegMaskBitsInBlock(MBB->getNumber());
645 } else {
646 Slots = getRegMaskSlots();
647 Bits = getRegMaskBits();
648 }
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000649
650 // We are going to enumerate all the register mask slots contained in LI.
651 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000652 ArrayRef<SlotIndex>::iterator SlotI =
653 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
654 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
655
656 // No slots in range, LI begins after the last call.
657 if (SlotI == SlotE)
658 return false;
659
660 bool Found = false;
661 for (;;) {
662 assert(*SlotI >= LiveI->start);
663 // Loop over all slots overlapping this segment.
664 while (*SlotI < LiveI->end) {
665 // *SlotI overlaps LI. Collect mask bits.
666 if (!Found) {
667 // This is the first overlap. Initialize UsableRegs to all ones.
668 UsableRegs.clear();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000669 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000670 Found = true;
671 }
672 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000673 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000674 if (++SlotI == SlotE)
675 return Found;
676 }
677 // *SlotI is beyond the current LI segment.
678 LiveI = LI.advanceTo(LiveI, *SlotI);
679 if (LiveI == LiveE)
680 return Found;
681 // Advance SlotI until it overlaps.
682 while (*SlotI < LiveI->start)
683 if (++SlotI == SlotE)
684 return Found;
685 }
686}
Lang Hames3dc7c512012-02-17 18:44:18 +0000687
688//===----------------------------------------------------------------------===//
689// IntervalUpdate class.
690//===----------------------------------------------------------------------===//
691
Lang Hamesfd6d3212012-02-21 00:00:36 +0000692// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hames3dc7c512012-02-17 18:44:18 +0000693class LiveIntervals::HMEditor {
694private:
Lang Hamesecb50622012-02-17 23:43:40 +0000695 LiveIntervals& LIS;
696 const MachineRegisterInfo& MRI;
697 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000698 SlotIndex OldIdx;
Lang Hamesecb50622012-02-17 23:43:40 +0000699 SlotIndex NewIdx;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000700 SmallPtrSet<LiveInterval*, 8> Updated;
Andrew Trick27c28ce2012-10-16 00:22:51 +0000701 bool UpdateFlags;
Lang Hames6aceab12012-02-19 07:13:05 +0000702
Lang Hames3dc7c512012-02-17 18:44:18 +0000703public:
Lang Hamesecb50622012-02-17 23:43:40 +0000704 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000705 const TargetRegisterInfo& TRI,
Andrew Trick27c28ce2012-10-16 00:22:51 +0000706 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
707 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
708 UpdateFlags(UpdateFlags) {}
709
710 // FIXME: UpdateFlags is a workaround that creates live intervals for all
711 // physregs, even those that aren't needed for regalloc, in order to update
712 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
713 // flags, and postRA passes will use a live register utility instead.
714 LiveInterval *getRegUnitLI(unsigned Unit) {
715 if (UpdateFlags)
716 return &LIS.getRegUnit(Unit);
717 return LIS.getCachedRegUnit(Unit);
718 }
Lang Hames3dc7c512012-02-17 18:44:18 +0000719
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000720 /// Update all live ranges touched by MI, assuming a move from OldIdx to
721 /// NewIdx.
722 void updateAllRanges(MachineInstr *MI) {
723 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
724 bool hasRegMask = false;
725 for (MIOperands MO(MI); MO.isValid(); ++MO) {
726 if (MO->isRegMask())
727 hasRegMask = true;
728 if (!MO->isReg())
Lang Hames4586d252012-02-21 22:29:38 +0000729 continue;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000730 // Aggressively clear all kill flags.
731 // They are reinserted by VirtRegRewriter.
732 if (MO->isUse())
733 MO->setIsKill(false);
734
735 unsigned Reg = MO->getReg();
736 if (!Reg)
737 continue;
738 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
739 updateRange(LIS.getInterval(Reg));
740 continue;
741 }
742
743 // For physregs, only update the regunits that actually have a
744 // precomputed live range.
745 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Andrew Trick27c28ce2012-10-16 00:22:51 +0000746 if (LiveInterval *LI = getRegUnitLI(*Units))
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000747 updateRange(*LI);
Lang Hames4586d252012-02-21 22:29:38 +0000748 }
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000749 if (hasRegMask)
750 updateRegMaskSlots();
Lang Hames6aceab12012-02-19 07:13:05 +0000751 }
752
Lang Hames55fed622012-02-19 03:00:30 +0000753private:
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000754 /// Update a single live range, assuming an instruction has been moved from
755 /// OldIdx to NewIdx.
756 void updateRange(LiveInterval &LI) {
757 if (!Updated.insert(&LI))
758 return;
759 DEBUG({
760 dbgs() << " ";
761 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
762 dbgs() << PrintReg(LI.reg);
Jakob Stoklund Olesenbf833f02012-06-19 23:50:18 +0000763 else
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000764 dbgs() << PrintRegUnit(LI.reg, &TRI);
765 dbgs() << ":\t" << LI << '\n';
766 });
767 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
768 handleMoveDown(LI);
769 else
770 handleMoveUp(LI);
771 DEBUG(dbgs() << " -->\t" << LI << '\n');
772 LI.verify();
Lang Hames3dc7c512012-02-17 18:44:18 +0000773 }
774
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000775 /// Update LI to reflect an instruction has been moved downwards from OldIdx
776 /// to NewIdx.
777 ///
778 /// 1. Live def at OldIdx:
779 /// Move def to NewIdx, assert endpoint after NewIdx.
780 ///
781 /// 2. Live def at OldIdx, killed at NewIdx:
782 /// Change to dead def at NewIdx.
783 /// (Happens when bundling def+kill together).
784 ///
785 /// 3. Dead def at OldIdx:
786 /// Move def to NewIdx, possibly across another live value.
787 ///
788 /// 4. Def at OldIdx AND at NewIdx:
789 /// Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
790 /// (Happens when bundling multiple defs together).
791 ///
792 /// 5. Value read at OldIdx, killed before NewIdx:
793 /// Extend kill to NewIdx.
794 ///
795 void handleMoveDown(LiveInterval &LI) {
796 // First look for a kill at OldIdx.
797 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
798 LiveInterval::iterator E = LI.end();
799 // Is LI even live at OldIdx?
800 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
801 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000802
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000803 // Handle a live-in value.
804 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
805 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
806 // If the live-in value already extends to NewIdx, there is nothing to do.
807 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
808 return;
809 // Aggressively remove all kill flags from the old kill point.
810 // Kill flags shouldn't be used while live intervals exist, they will be
811 // reinserted by VirtRegRewriter.
812 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
813 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
814 if (MO->isReg() && MO->isUse())
815 MO->setIsKill(false);
816 // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
817 // overlapping ranges. Case 5 above.
818 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
819 // If this was a kill, there may also be a def. Otherwise we're done.
820 if (!isKill)
821 return;
822 ++I;
Lang Hames6aceab12012-02-19 07:13:05 +0000823 }
824
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000825 // Check for a def at OldIdx.
826 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
827 return;
828 // We have a def at OldIdx.
829 VNInfo *DefVNI = I->valno;
830 assert(DefVNI->def == I->start && "Inconsistent def");
831 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
832 // If the defined value extends beyond NewIdx, just move the def down.
833 // This is case 1 above.
834 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
835 I->start = DefVNI->def;
836 return;
837 }
838 // The remaining possibilities are now:
839 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
840 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
841 // In either case, it is possible that there is an existing def at NewIdx.
842 assert((I->end == OldIdx.getDeadSlot() ||
843 SlotIndex::isSameInstr(I->end, NewIdx)) &&
844 "Cannot move def below kill");
845 LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
846 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
847 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
848 // coalesced into that value.
849 assert(NewI->valno != DefVNI && "Multiple defs of value?");
850 LI.removeValNo(DefVNI);
851 return;
852 }
853 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
854 // If the def at OldIdx was dead, we allow it to be moved across other LI
855 // values. The new range should be placed immediately before NewI, move any
856 // intermediate ranges up.
857 assert(NewI != I && "Inconsistent iterators");
858 std::copy(llvm::next(I), NewI, I);
859 *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
860 }
861
862 /// Update LI to reflect an instruction has been moved upwards from OldIdx
863 /// to NewIdx.
864 ///
865 /// 1. Live def at OldIdx:
866 /// Hoist def to NewIdx.
867 ///
868 /// 2. Dead def at OldIdx:
869 /// Hoist def+end to NewIdx, possibly move across other values.
870 ///
871 /// 3. Dead def at OldIdx AND existing def at NewIdx:
872 /// Remove value defined at OldIdx, coalescing it with existing value.
873 ///
874 /// 4. Live def at OldIdx AND existing def at NewIdx:
875 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
876 /// (Happens when bundling multiple defs together).
877 ///
878 /// 5. Value killed at OldIdx:
879 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
880 /// OldIdx.
881 ///
882 void handleMoveUp(LiveInterval &LI) {
883 // First look for a kill at OldIdx.
884 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
885 LiveInterval::iterator E = LI.end();
886 // Is LI even live at OldIdx?
887 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
888 return;
889
890 // Handle a live-in value.
891 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
892 // If the live-in value isn't killed here, there is nothing to do.
893 if (!SlotIndex::isSameInstr(OldIdx, I->end))
894 return;
895 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
896 // another use, we need to search for that use. Case 5 above.
897 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
898 ++I;
899 // If OldIdx also defines a value, there couldn't have been another use.
900 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
901 // No def, search for the new kill.
902 // This can never be an early clobber kill since there is no def.
903 llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
904 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000905 }
906 }
907
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000908 // Now deal with the def at OldIdx.
909 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
910 VNInfo *DefVNI = I->valno;
911 assert(DefVNI->def == I->start && "Inconsistent def");
912 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
913
914 // Check for an existing def at NewIdx.
915 LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
916 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
917 assert(NewI->valno != DefVNI && "Same value defined more than once?");
918 // There is an existing def at NewIdx.
919 if (I->end.isDead()) {
920 // Case 3: Remove the dead def at OldIdx.
921 LI.removeValNo(DefVNI);
922 return;
923 }
924 // Case 4: Replace def at NewIdx with live def at OldIdx.
925 I->start = DefVNI->def;
926 LI.removeValNo(NewI->valno);
927 return;
Lang Hames6aceab12012-02-19 07:13:05 +0000928 }
929
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000930 // There is no existing def at NewIdx. Hoist DefVNI.
931 if (!I->end.isDead()) {
932 // Leave the end point of a live def.
933 I->start = DefVNI->def;
934 return;
935 }
936
937 // DefVNI is a dead def. It may have been moved across other values in LI,
938 // so move I up to NewI. Slide [NewI;I) down one position.
939 std::copy_backward(NewI, I, llvm::next(I));
940 *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
Lang Hames6aceab12012-02-19 07:13:05 +0000941 }
942
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000943 void updateRegMaskSlots() {
Lang Hamesecb50622012-02-17 23:43:40 +0000944 SmallVectorImpl<SlotIndex>::iterator RI =
945 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
946 OldIdx);
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000947 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
948 "No RegMask at OldIdx.");
949 *RI = NewIdx.getRegSlot();
950 assert((RI == LIS.RegMaskSlots.begin() ||
951 SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
952 "Cannot move regmask instruction above another call");
953 assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
954 SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
955 "Cannot move regmask instruction below another call");
Lang Hamesfbc8dd32012-02-17 21:29:41 +0000956 }
Lang Hames55fed622012-02-19 03:00:30 +0000957
958 // Return the last use of reg between NewIdx and OldIdx.
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +0000959 SlotIndex findLastUseBefore(unsigned Reg) {
Lang Hames6d742cc2012-09-12 06:56:16 +0000960
961 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000962 SlotIndex LastUse = NewIdx;
Lang Hames6d742cc2012-09-12 06:56:16 +0000963 for (MachineRegisterInfo::use_nodbg_iterator
964 UI = MRI.use_nodbg_begin(Reg),
965 UE = MRI.use_nodbg_end();
966 UI != UE; UI.skipInstruction()) {
967 const MachineInstr* MI = &*UI;
968 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
969 if (InstSlot > LastUse && InstSlot < OldIdx)
970 LastUse = InstSlot;
971 }
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000972 return LastUse;
Lang Hames55fed622012-02-19 03:00:30 +0000973 }
Jakob Stoklund Olesen778ef972013-03-08 18:08:57 +0000974
975 // This is a regunit interval, so scanning the use list could be very
976 // expensive. Scan upwards from OldIdx instead.
977 assert(NewIdx < OldIdx && "Expected upwards move");
978 SlotIndexes *Indexes = LIS.getSlotIndexes();
979 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(NewIdx);
980
981 // OldIdx may not correspond to an instruction any longer, so set MII to
982 // point to the next instruction after OldIdx, or MBB->end().
983 MachineBasicBlock::iterator MII = MBB->end();
984 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
985 Indexes->getNextNonNullIndex(OldIdx)))
986 if (MI->getParent() == MBB)
987 MII = MI;
988
989 MachineBasicBlock::iterator Begin = MBB->begin();
990 while (MII != Begin) {
991 if ((--MII)->isDebugValue())
992 continue;
993 SlotIndex Idx = Indexes->getInstructionIndex(MII);
994
995 // Stop searching when NewIdx is reached.
996 if (!SlotIndex::isEarlierInstr(NewIdx, Idx))
997 return NewIdx;
998
999 // Check if MII uses Reg.
1000 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1001 if (MO->isReg() &&
1002 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1003 TRI.hasRegUnit(MO->getReg(), Reg))
1004 return Idx;
1005 }
1006 // Didn't reach NewIdx. It must be the first instruction in the block.
1007 return NewIdx;
Lang Hames55fed622012-02-19 03:00:30 +00001008 }
Lang Hames3dc7c512012-02-17 18:44:18 +00001009};
1010
Andrew Trick27c28ce2012-10-16 00:22:51 +00001011void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001012 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001013 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1014 Indexes->removeMachineInstrFromMaps(MI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001015 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
Lang Hamesecb50622012-02-17 23:43:40 +00001016 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1017 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hames3dc7c512012-02-17 18:44:18 +00001018 "Cannot handle moves across basic block boundaries.");
Lang Hames3dc7c512012-02-17 18:44:18 +00001019
Andrew Trick27c28ce2012-10-16 00:22:51 +00001020 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001021 HME.updateAllRanges(MI);
Lang Hames4586d252012-02-21 22:29:38 +00001022}
1023
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +00001024void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trick27c28ce2012-10-16 00:22:51 +00001025 MachineInstr* BundleStart,
1026 bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001027 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001028 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
Andrew Trick27c28ce2012-10-16 00:22:51 +00001029 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001030 HME.updateAllRanges(MI);
Lang Hames3dc7c512012-02-17 18:44:18 +00001031}
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001032
1033void
1034LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001035 MachineBasicBlock::iterator Begin,
1036 MachineBasicBlock::iterator End,
Cameron Zwarich7324d4e2013-02-17 03:48:23 +00001037 ArrayRef<unsigned> OrigRegs) {
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001038 // Find anchor points, which are at the beginning/end of blocks or at
1039 // instructions that already have indexes.
1040 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1041 --Begin;
1042 while (End != MBB->end() && !Indexes->hasIndex(End))
1043 ++End;
1044
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001045 SlotIndex endIdx;
1046 if (End == MBB->end())
1047 endIdx = getMBBEndIdx(MBB).getPrevSlot();
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001048 else
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001049 endIdx = getInstructionIndex(End);
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001050
Cameron Zwarich349cf342013-02-20 06:46:41 +00001051 Indexes->repairIndexesInRange(MBB, Begin, End);
1052
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001053 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1054 --I;
1055 MachineInstr *MI = I;
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001056 if (MI->isDebugValue())
1057 continue;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001058 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1059 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1060 if (MOI->isReg() &&
1061 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1062 !hasInterval(MOI->getReg())) {
1063 LiveInterval &LI = getOrCreateInterval(MOI->getReg());
1064 computeVirtRegInterval(&LI);
1065 }
1066 }
1067 }
1068
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001069 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1070 unsigned Reg = OrigRegs[i];
1071 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1072 continue;
1073
1074 LiveInterval &LI = getInterval(Reg);
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001075 // FIXME: Should we support undefs that gain defs?
1076 if (!LI.hasAtLeastOneValue())
1077 continue;
1078
1079 LiveInterval::iterator LII = LI.find(endIdx);
1080 SlotIndex lastUseIdx;
1081 if (LII != LI.end() && LII->start < endIdx)
1082 lastUseIdx = LII->end;
1083 else
1084 --LII;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001085
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001086 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1087 --I;
1088 MachineInstr *MI = I;
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001089 if (MI->isDebugValue())
1090 continue;
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001091
Cameron Zwarich79f5ab12013-02-23 10:25:25 +00001092 SlotIndex instrIdx = getInstructionIndex(MI);
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001093 bool isStartValid = getInstructionFromIndex(LII->start);
1094 bool isEndValid = getInstructionFromIndex(LII->end);
1095
1096 // FIXME: This doesn't currently handle early-clobber or multiple removed
1097 // defs inside of the region to repair.
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001098 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1099 OE = MI->operands_end(); OI != OE; ++OI) {
1100 const MachineOperand &MO = *OI;
1101 if (!MO.isReg() || MO.getReg() != Reg)
1102 continue;
1103
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001104 if (MO.isDef()) {
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001105 if (!isStartValid) {
1106 if (LII->end.isDead()) {
1107 SlotIndex prevStart;
1108 if (LII != LI.begin())
1109 prevStart = llvm::prior(LII)->start;
1110
1111 // FIXME: This could be more efficient if there was a removeRange
1112 // method that returned an iterator.
1113 LI.removeRange(*LII, true);
1114 if (prevStart.isValid())
1115 LII = LI.find(prevStart);
1116 else
1117 LII = LI.begin();
1118 } else {
1119 LII->start = instrIdx.getRegSlot();
1120 LII->valno->def = instrIdx.getRegSlot();
1121 if (MO.getSubReg() && !MO.isUndef())
1122 lastUseIdx = instrIdx.getRegSlot();
1123 else
1124 lastUseIdx = SlotIndex();
1125 continue;
1126 }
1127 }
1128
1129 if (!lastUseIdx.isValid()) {
1130 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1131 VNInfoAllocator);
1132 LiveRange LR(instrIdx.getRegSlot(), instrIdx.getDeadSlot(), VNI);
1133 LII = LI.addRange(LR);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001134 } else if (LII->start != instrIdx.getRegSlot()) {
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001135 VNInfo *VNI = LI.getNextValue(instrIdx.getRegSlot(),
1136 VNInfoAllocator);
1137 LiveRange LR(instrIdx.getRegSlot(), lastUseIdx, VNI);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001138 LII = LI.addRange(LR);
1139 }
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001140
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001141 if (MO.getSubReg() && !MO.isUndef())
1142 lastUseIdx = instrIdx.getRegSlot();
1143 else
1144 lastUseIdx = SlotIndex();
1145 } else if (MO.isUse()) {
1146 // FIXME: This should probably be handled outside of this branch,
1147 // either as part of the def case (for defs inside of the region) or
1148 // after the loop over the region.
1149 if (!isEndValid && !LII->end.isBlock())
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001150 LII->end = instrIdx.getRegSlot();
Cameron Zwarich0e827eb2013-02-20 22:09:57 +00001151 if (!lastUseIdx.isValid())
1152 lastUseIdx = instrIdx.getRegSlot();
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001153 }
1154 }
1155 }
1156 }
1157}