blob: 5df37da539128cca10090bdaf53e75c2a55a2378 [file] [log] [blame]
Chris Lattner85638332004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Evlogimenos0e9ded72003-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
Matthias Braunbbb528f2016-02-13 04:35:31 +000012// basic blocks of the function in DFS order and computes live intervals for
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000013// each virtual and physical register.
14//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerb1f89822005-09-21 04:19:09 +000017#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "LiveRangeCalc.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/STLExtras.h"
Dan Gohman09b04482008-07-25 00:02:30 +000021#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000022#include "llvm/CodeGen/LiveVariables.h"
Michael Gottesman9f49d742013-12-14 00:53:32 +000023#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000024#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000027#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000028#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Value.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000030#include "llvm/Support/BlockFrequency.h"
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +000031#include "llvm/Support/CommandLine.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000037#include "llvm/Target/TargetSubtargetInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000038#include <algorithm>
Jeff Cohencc08c832006-12-02 02:22:01 +000039#include <cmath>
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include <limits>
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "regalloc"
44
Devang Patel8c78a0b2007-05-03 01:11:54 +000045char LiveIntervals::ID = 0;
Jakob Stoklund Olesen1c465892012-08-03 22:12:54 +000046char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +000047INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
48 "Live Interval Analysis", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +000049INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Andrew Trickd3f8fe82012-02-10 04:10:36 +000050INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson8ac477f2010-10-12 19:48:12 +000051INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson8ac477f2010-10-12 19:48:12 +000052INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersondf7a4f22010-10-07 22:25:06 +000053 "Live Interval Analysis", false, false)
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000054
Andrew Trick8d02e912013-06-21 18:33:23 +000055#ifndef NDEBUG
56static cl::opt<bool> EnablePrecomputePhysRegs(
57 "precompute-phys-liveness", cl::Hidden,
58 cl::desc("Eagerly compute live intervals for all physreg units."));
59#else
60static bool EnablePrecomputePhysRegs = false;
61#endif // NDEBUG
62
Matthias Braune3d3b882014-12-10 01:12:30 +000063static cl::opt<bool> EnableSubRegLiveness(
64 "enable-subreg-liveness", cl::Hidden, cl::init(true),
65 cl::desc("Enable subregister liveness tracking."));
66
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000067namespace llvm {
68cl::opt<bool> UseSegmentSetForPhysRegs(
69 "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
70 cl::desc(
71 "Use segment set for the computation of the live ranges of physregs."));
72}
73
Chris Lattnerbdf12102006-08-24 22:43:55 +000074void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman04023152009-07-31 23:37:33 +000075 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +000076 AU.addRequired<AAResultsWrapperPass>();
77 AU.addPreserved<AAResultsWrapperPass>();
Evan Cheng16bfe5b2010-08-17 21:00:37 +000078 AU.addPreserved<LiveVariables>();
Andrew Trick5188c002012-02-13 20:44:42 +000079 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +000080 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling0c209432008-01-04 20:54:55 +000081 AU.addPreservedID(MachineDominatorsID);
Lang Hames05fb9632009-11-03 23:52:08 +000082 AU.addPreserved<SlotIndexes>();
83 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenosa6983082004-08-04 09:46:26 +000084 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +000085}
86
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000087LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
Craig Topperc0196b12014-04-14 00:51:57 +000088 DomTree(nullptr), LRCalc(nullptr) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +000089 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
90}
91
92LiveIntervals::~LiveIntervals() {
93 delete LRCalc;
94}
95
Chris Lattnerbdf12102006-08-24 22:43:55 +000096void LiveIntervals::releaseMemory() {
Owen Anderson51f689a2008-08-13 21:49:13 +000097 // Free the live intervals themselves.
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +000098 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
99 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
100 VirtRegIntervals.clear();
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000101 RegMaskSlots.clear();
102 RegMaskBits.clear();
Jakob Stoklund Olesen25c41952012-02-10 01:26:29 +0000103 RegMaskBlocks.clear();
Lang Hamesdab7b062009-07-09 03:57:02 +0000104
Matthias Braun34e1be92013-10-10 21:29:02 +0000105 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
106 delete RegUnitRanges[i];
107 RegUnitRanges.clear();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000108
Benjamin Kramera0000022010-06-26 11:30:59 +0000109 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
110 VNInfoAllocator.Reset();
Alkis Evlogimenos50d97e32004-01-31 19:59:32 +0000111}
112
Jakob Stoklund Olesen6d13b8f2013-08-14 17:28:46 +0000113/// runOnMachineFunction - calculates LiveIntervals
Owen Anderson4f8e1ad2008-05-28 20:54:50 +0000114///
115bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000116 MF = &fn;
117 MRI = &MF->getRegInfo();
Eric Christopherd3fa4402014-10-14 06:26:53 +0000118 TRI = MF->getSubtarget().getRegisterInfo();
119 TII = MF->getSubtarget().getInstrInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000120 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000121 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000122 DomTree = &getAnalysis<MachineDominatorTree>();
Matthias Braune3d3b882014-12-10 01:12:30 +0000123
124 if (EnableSubRegLiveness && MF->getSubtarget().enableSubRegLiveness())
125 MRI->enableSubRegLiveness(true);
126
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000127 if (!LRCalc)
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000128 LRCalc = new LiveRangeCalc();
Owen Anderson4f8e1ad2008-05-28 20:54:50 +0000129
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000130 // Allocate space for all virtual registers.
131 VirtRegIntervals.resize(MRI->getNumVirtRegs());
132
Jakob Stoklund Olesenfac770b2013-02-09 00:04:07 +0000133 computeVirtRegs();
134 computeRegMasks();
Jakob Stoklund Olesen51c63e62012-06-20 23:31:34 +0000135 computeLiveInRegUnits();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000136
Andrew Trick8d02e912013-06-21 18:33:23 +0000137 if (EnablePrecomputePhysRegs) {
138 // For stress testing, precompute live ranges of all physical register
139 // units, including reserved registers.
140 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
141 getRegUnit(i);
142 }
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000143 DEBUG(dump());
Alkis Evlogimenosa6983082004-08-04 09:46:26 +0000144 return true;
Alkis Evlogimenos0e9ded72003-11-20 03:32:25 +0000145}
146
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000147/// print - Implement the dump method.
Chris Lattner13626022009-08-23 06:03:38 +0000148void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattnera6f074f2009-08-23 03:41:05 +0000149 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesen20d25a72012-02-14 23:46:21 +0000150
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000151 // Dump the regunits.
Matthias Braun34e1be92013-10-10 21:29:02 +0000152 for (unsigned i = 0, e = RegUnitRanges.size(); i != e; ++i)
153 if (LiveRange *LR = RegUnitRanges[i])
Matthias Braunf6fe6bf2013-10-10 21:29:05 +0000154 OS << PrintRegUnit(i, TRI) << ' ' << *LR << '\n';
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000155
Jakob Stoklund Olesen20d25a72012-02-14 23:46:21 +0000156 // Dump the virtregs.
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +0000157 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
158 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
159 if (hasInterval(Reg))
Matthias Braunf6fe6bf2013-10-10 21:29:05 +0000160 OS << getInterval(Reg) << '\n';
Jakob Stoklund Olesenc61edda2012-06-22 20:37:52 +0000161 }
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000162
Jakob Stoklund Olesen13d55622012-11-09 19:18:49 +0000163 OS << "RegMasks:";
164 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
165 OS << ' ' << RegMaskSlots[i];
166 OS << '\n';
167
Evan Cheng7f789592009-09-14 21:33:42 +0000168 printInstrs(OS);
169}
170
171void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattnera6f074f2009-08-23 03:41:05 +0000172 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000173 MF->print(OS, Indexes);
Chris Lattnerb0b707f2004-09-30 15:59:17 +0000174}
175
Manman Ren19f49ac2012-09-11 22:23:19 +0000176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng7f789592009-09-14 21:33:42 +0000177void LiveIntervals::dumpInstrs() const {
David Greene1a51a212010-01-04 22:49:02 +0000178 printInstrs(dbgs());
Evan Cheng7f789592009-09-14 21:33:42 +0000179}
Manman Ren742534c2012-09-06 19:06:06 +0000180#endif
Evan Cheng7f789592009-09-14 21:33:42 +0000181
Owen Anderson51f689a2008-08-13 21:49:13 +0000182LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Aaron Ballman04999042013-11-13 00:15:44 +0000183 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
184 llvm::huge_valf : 0.0F;
Owen Anderson51f689a2008-08-13 21:49:13 +0000185 return new LiveInterval(reg, Weight);
Alkis Evlogimenos237f2032004-04-09 18:07:57 +0000186}
Evan Chengbe51f282007-11-12 06:35:08 +0000187
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000188
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000189/// computeVirtRegInterval - Compute the live interval of a virtual register,
190/// based on defs and uses.
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000191void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000192 assert(LRCalc && "LRCalc not initialized.");
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000193 assert(LI.empty() && "Should only compute empty intervals.");
Matthias Braun73e42212015-09-22 22:37:44 +0000194 bool ShouldTrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(LI.reg);
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000195 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
Matthias Braun73e42212015-09-22 22:37:44 +0000196 LRCalc->calculate(LI, ShouldTrackSubRegLiveness);
197 bool SeparatedComponents = computeDeadValues(LI, nullptr);
198 if (SeparatedComponents) {
199 assert(ShouldTrackSubRegLiveness
200 && "Separated components should only occur for unused subreg defs");
201 SmallVector<LiveInterval*, 8> SplitLIs;
202 splitSeparateComponents(LI, SplitLIs);
203 }
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000204}
205
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000206void LiveIntervals::computeVirtRegs() {
207 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
208 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
209 if (MRI->reg_nodbg_empty(Reg))
210 continue;
Mark Lacey9d8103d2013-08-14 23:50:16 +0000211 createAndComputeVirtRegInterval(Reg);
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000212 }
213}
214
215void LiveIntervals::computeRegMasks() {
216 RegMaskBlocks.resize(MF->getNumBlockIDs());
217
218 // Find all instructions with regmask operands.
Reid Klecknere535c1f2015-11-06 02:01:02 +0000219 for (MachineBasicBlock &MBB : *MF) {
220 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000221 RMB.first = RegMaskSlots.size();
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000222
223 // Some block starts, such as EH funclets, create masks.
224 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
225 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
226 RegMaskBits.push_back(Mask);
227 }
228
Reid Klecknere535c1f2015-11-06 02:01:02 +0000229 for (MachineInstr &MI : MBB) {
230 for (const MachineOperand &MO : MI.operands()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000231 if (!MO.isRegMask())
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000232 continue;
Reid Klecknere535c1f2015-11-06 02:01:02 +0000233 RegMaskSlots.push_back(Indexes->getInstructionIndex(&MI).getRegSlot());
234 RegMaskBits.push_back(MO.getRegMask());
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000235 }
Reid Klecknere535c1f2015-11-06 02:01:02 +0000236 }
Reid Klecknerb8fd1622015-11-06 17:06:38 +0000237
238 // Some block ends, such as funclet returns, create masks.
239 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
240 RegMaskSlots.push_back(Indexes->getMBBEndIdx(&MBB));
241 RegMaskBits.push_back(Mask);
242 }
243
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000244 // Compute the number of register mask instructions in this block.
Dmitri Gribenkoca1e27b2012-09-10 21:26:47 +0000245 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesen7dfe7ab2012-07-27 21:56:39 +0000246 }
247}
Jakob Stoklund Olesen4021a7b2012-07-27 20:58:46 +0000248
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000249//===----------------------------------------------------------------------===//
250// Register Unit Liveness
251//===----------------------------------------------------------------------===//
252//
253// Fixed interference typically comes from ABI boundaries: Function arguments
254// and return values are passed in fixed registers, and so are exception
255// pointers entering landing pads. Certain instructions require values to be
256// present in specific registers. That is also represented through fixed
257// interference.
258//
259
Matthias Braun34e1be92013-10-10 21:29:02 +0000260/// computeRegUnitInterval - Compute the live range of a register unit, based
261/// on the uses and defs of aliasing registers. The range should be empty,
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000262/// or contain only dead phi-defs from ABI blocks.
Matthias Braun34e1be92013-10-10 21:29:02 +0000263void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000264 assert(LRCalc && "LRCalc not initialized.");
265 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
266
267 // The physregs aliasing Unit are the roots and their super-registers.
268 // Create all values as dead defs before extending to uses. Note that roots
269 // may share super-registers. That's OK because createDeadDefs() is
270 // idempotent. It is very rare for a register unit to have multiple roots, so
271 // uniquing super-registers is probably not worthwhile.
272 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
Chad Rosier682ae152013-05-22 22:36:55 +0000273 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
274 Supers.isValid(); ++Supers) {
Matthias Braunc3a72c22014-12-15 21:36:35 +0000275 if (!MRI->reg_empty(*Supers))
276 LRCalc->createDeadDefs(LR, *Supers);
277 }
278 }
279
280 // Now extend LR to reach all uses.
281 // Ignore uses of reserved registers. We only track defs of those.
282 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
283 for (MCSuperRegIterator Supers(*Roots, TRI, /*IncludeSelf=*/true);
284 Supers.isValid(); ++Supers) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000285 unsigned Reg = *Supers;
Matthias Braunc3a72c22014-12-15 21:36:35 +0000286 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
287 LRCalc->extendToUses(LR, Reg);
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000288 }
289 }
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000290
291 // Flush the segment set to the segment vector.
292 if (UseSegmentSetForPhysRegs)
293 LR.flushSegmentSet();
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000294}
295
296
297/// computeLiveInRegUnits - Precompute the live ranges of any register units
298/// that are live-in to an ABI block somewhere. Register values can appear
299/// without a corresponding def when entering the entry block or a landing pad.
300///
301void LiveIntervals::computeLiveInRegUnits() {
Matthias Braun34e1be92013-10-10 21:29:02 +0000302 RegUnitRanges.resize(TRI->getNumRegUnits());
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000303 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
304
Matthias Braun34e1be92013-10-10 21:29:02 +0000305 // Keep track of the live range sets allocated.
306 SmallVector<unsigned, 8> NewRanges;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000307
308 // Check all basic blocks for live-ins.
309 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
310 MFI != MFE; ++MFI) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000311 const MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000312
313 // We only care about ABI blocks: Entry + landing pads.
Reid Kleckner0e288232015-08-27 23:27:47 +0000314 if ((MFI != MF->begin() && !MBB->isEHPad()) || MBB->livein_empty())
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000315 continue;
316
317 // Create phi-defs at Begin for all live-in registers.
318 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
319 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
Matthias Braund9da1622015-09-09 18:08:03 +0000320 for (const auto &LI : MBB->liveins()) {
321 for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000322 unsigned Unit = *Units;
Matthias Braun34e1be92013-10-10 21:29:02 +0000323 LiveRange *LR = RegUnitRanges[Unit];
324 if (!LR) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000325 // Use segment set to speed-up initial computation of the live range.
326 LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
Matthias Braun34e1be92013-10-10 21:29:02 +0000327 NewRanges.push_back(Unit);
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000328 }
Matthias Braun34e1be92013-10-10 21:29:02 +0000329 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay7ba769b2012-06-05 23:00:03 +0000330 (void)VNI;
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000331 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
332 }
333 }
334 DEBUG(dbgs() << '\n');
335 }
Matthias Braun34e1be92013-10-10 21:29:02 +0000336 DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000337
Matthias Braun34e1be92013-10-10 21:29:02 +0000338 // Compute the 'normal' part of the ranges.
339 for (unsigned i = 0, e = NewRanges.size(); i != e; ++i) {
340 unsigned Unit = NewRanges[i];
341 computeRegUnitRange(*RegUnitRanges[Unit], Unit);
342 }
Jakob Stoklund Olesen12e03da2012-06-05 22:02:15 +0000343}
344
345
Matthias Braun20e1f382014-12-10 01:12:18 +0000346static void createSegmentsForValues(LiveRange &LR,
347 iterator_range<LiveInterval::vni_iterator> VNIs) {
348 for (auto VNI : VNIs) {
349 if (VNI->isUnused())
350 continue;
351 SlotIndex Def = VNI->def;
352 LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
353 }
354}
355
356typedef SmallVector<std::pair<SlotIndex, VNInfo*>, 16> ShrinkToUsesWorkList;
357
358static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
359 ShrinkToUsesWorkList &WorkList,
360 const LiveRange &OldRange) {
361 // Keep track of the PHIs that are in use.
362 SmallPtrSet<VNInfo*, 8> UsedPHIs;
363 // Blocks that have already been added to WorkList as live-out.
364 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
365
366 // Extend intervals to reach all uses in WorkList.
367 while (!WorkList.empty()) {
368 SlotIndex Idx = WorkList.back().first;
369 VNInfo *VNI = WorkList.back().second;
370 WorkList.pop_back();
371 const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
372 SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
373
374 // Extend the live range for VNI to be live at Idx.
375 if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
376 assert(ExtVNI == VNI && "Unexpected existing value number");
377 (void)ExtVNI;
378 // Is this a PHIDef we haven't seen before?
379 if (!VNI->isPHIDef() || VNI->def != BlockStart ||
380 !UsedPHIs.insert(VNI).second)
381 continue;
382 // The PHI is live, make sure the predecessors are live-out.
383 for (auto &Pred : MBB->predecessors()) {
384 if (!LiveOut.insert(Pred).second)
385 continue;
386 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
387 // A predecessor is not required to have a live-out value for a PHI.
388 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
389 WorkList.push_back(std::make_pair(Stop, PVNI));
390 }
391 continue;
392 }
393
394 // VNI is live-in to MBB.
395 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
396 LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
397
398 // Make sure VNI is live-out from the predecessors.
399 for (auto &Pred : MBB->predecessors()) {
400 if (!LiveOut.insert(Pred).second)
401 continue;
402 SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
403 assert(OldRange.getVNInfoBefore(Stop) == VNI &&
404 "Wrong value out of predecessor");
405 WorkList.push_back(std::make_pair(Stop, VNI));
406 }
407 }
408}
409
Jakob Stoklund Olesen86308402011-03-17 20:37:07 +0000410bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000411 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000412 DEBUG(dbgs() << "Shrink: " << *li << '\n');
413 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hamesc405ac42012-01-03 20:05:57 +0000414 && "Can only shrink virtual registers");
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000415
Matthias Braun20e1f382014-12-10 01:12:18 +0000416 // Shrink subregister live ranges.
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000417 bool NeedsCleanup = false;
Matthias Braun09afa1e2014-12-11 00:59:06 +0000418 for (LiveInterval::SubRange &S : li->subranges()) {
419 shrinkToUses(S, li->reg);
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000420 if (S.empty())
421 NeedsCleanup = true;
Matthias Braun20e1f382014-12-10 01:12:18 +0000422 }
Matthias Braun0d4cebd2015-07-16 18:55:35 +0000423 if (NeedsCleanup)
424 li->removeEmptySubRanges();
Matthias Braun20e1f382014-12-10 01:12:18 +0000425
426 // Find all the values used, including PHI kills.
427 ShrinkToUsesWorkList WorkList;
Jakob Stoklund Olesenb8b1d4c2011-09-15 15:24:16 +0000428
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000429 // Visit all instructions reading li->reg.
Owen Andersonabb90c92014-03-13 06:02:25 +0000430 for (MachineRegisterInfo::reg_instr_iterator
431 I = MRI->reg_instr_begin(li->reg), E = MRI->reg_instr_end();
432 I != E; ) {
433 MachineInstr *UseMI = &*(I++);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000434 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
435 continue;
Jakob Stoklund Olesen69797902011-11-13 23:53:25 +0000436 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000437 LiveQueryResult LRQ = li->Query(Idx);
Jakob Stoklund Olesen02d83e32012-05-20 02:54:52 +0000438 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesenfdc09942011-03-18 03:06:04 +0000439 if (!VNI) {
440 // This shouldn't happen: readsVirtualRegister returns true, but there is
441 // no live value. It is likely caused by a target getting <undef> flags
442 // wrong.
443 DEBUG(dbgs() << Idx << '\t' << *UseMI
444 << "Warning: Instr claims to read non-existent value in "
445 << *li << '\n');
446 continue;
447 }
Jakob Stoklund Olesen7e6004a2011-11-14 18:45:38 +0000448 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen02d83e32012-05-20 02:54:52 +0000449 // register one slot early.
450 if (VNInfo *DefVNI = LRQ.valueDefined())
451 Idx = DefVNI->def;
452
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000453 WorkList.push_back(std::make_pair(Idx, VNI));
454 }
455
Matthias Braund7df9352013-10-10 21:28:47 +0000456 // Create new live ranges with only minimal live segments per def.
457 LiveRange NewLR;
Matthias Braun20e1f382014-12-10 01:12:18 +0000458 createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
459 extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000460
Pete Cooper72235572014-06-03 22:42:10 +0000461 // Move the trimmed segments back.
462 li->segments.swap(NewLR.segments);
Matthias Braun15abf372014-12-18 19:58:52 +0000463
464 // Handle dead values.
465 bool CanSeparate = computeDeadValues(*li, dead);
Pete Cooper72235572014-06-03 22:42:10 +0000466 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
467 return CanSeparate;
468}
469
Matthias Braun15abf372014-12-18 19:58:52 +0000470bool LiveIntervals::computeDeadValues(LiveInterval &LI,
Pete Cooper72235572014-06-03 22:42:10 +0000471 SmallVectorImpl<MachineInstr*> *dead) {
Matthias Braun73e42212015-09-22 22:37:44 +0000472 bool MayHaveSplitComponents = false;
Matthias Braun15abf372014-12-18 19:58:52 +0000473 for (auto VNI : LI.valnos) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000474 if (VNI->isUnused())
475 continue;
Matthias Braunc1988f32015-01-21 22:55:13 +0000476 SlotIndex Def = VNI->def;
477 LiveRange::iterator I = LI.FindSegmentContaining(Def);
Matthias Braun15abf372014-12-18 19:58:52 +0000478 assert(I != LI.end() && "Missing segment for VNI");
Matthias Braunc1988f32015-01-21 22:55:13 +0000479
480 // Is the register live before? Otherwise we may have to add a read-undef
481 // flag for subregister defs.
Matthias Braun73e42212015-09-22 22:37:44 +0000482 bool DeadBeforeDef = false;
483 unsigned VReg = LI.reg;
484 if (MRI->shouldTrackSubRegLiveness(VReg)) {
Matthias Braunc1988f32015-01-21 22:55:13 +0000485 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
486 MachineInstr *MI = getInstructionFromIndex(Def);
Matthias Braun2c98d0f2015-11-11 00:41:58 +0000487 MI->setRegisterDefReadUndef(VReg);
Matthias Braun73e42212015-09-22 22:37:44 +0000488 DeadBeforeDef = true;
Matthias Braunc1988f32015-01-21 22:55:13 +0000489 }
490 }
491
492 if (I->end != Def.getDeadSlot())
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000493 continue;
Jakob Stoklund Olesen81eb18d2011-03-02 00:33:01 +0000494 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000495 // This is a dead PHI. Remove it.
Jakob Stoklund Olesendaae19f2012-08-03 20:59:32 +0000496 VNI->markUnused();
Matthias Braun15abf372014-12-18 19:58:52 +0000497 LI.removeSegment(I);
Matthias Braunc1988f32015-01-21 22:55:13 +0000498 DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
Matthias Braun73e42212015-09-22 22:37:44 +0000499 MayHaveSplitComponents = true;
Matthias Braun15abf372014-12-18 19:58:52 +0000500 } else {
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000501 // This is a dead def. Make sure the instruction knows.
Matthias Braunc1988f32015-01-21 22:55:13 +0000502 MachineInstr *MI = getInstructionFromIndex(Def);
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000503 assert(MI && "No instruction defining live value");
Matthias Braun73e42212015-09-22 22:37:44 +0000504 MI->addRegisterDead(VReg, TRI);
505
506 // If we have a dead def that is completely separate from the rest of
507 // the liverange then we rewrite it to use a different VReg to not violate
508 // the rule that the liveness of a virtual register forms a connected
509 // component. This should only happen if subregister liveness is tracked.
510 if (DeadBeforeDef)
511 MayHaveSplitComponents = true;
512
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000513 if (dead && MI->allDefsAreDead()) {
Matthias Braunc1988f32015-01-21 22:55:13 +0000514 DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
Jakob Stoklund Olesen71c380f2011-03-07 23:29:10 +0000515 dead->push_back(MI);
516 }
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000517 }
518 }
Matthias Braun73e42212015-09-22 22:37:44 +0000519 return MayHaveSplitComponents;
Matthias Braun20e1f382014-12-10 01:12:18 +0000520}
521
Matthias Braun15abf372014-12-18 19:58:52 +0000522void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg)
Matthias Braun20e1f382014-12-10 01:12:18 +0000523{
524 DEBUG(dbgs() << "Shrink: " << SR << '\n');
525 assert(TargetRegisterInfo::isVirtualRegister(Reg)
526 && "Can only shrink virtual registers");
527 // Find all the values used, including PHI kills.
528 ShrinkToUsesWorkList WorkList;
529
530 // Visit all instructions reading Reg.
531 SlotIndex LastIdx;
532 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
533 MachineInstr *UseMI = MO.getParent();
534 if (UseMI->isDebugValue())
535 continue;
536 // Maybe the operand is for a subregister we don't care about.
537 unsigned SubReg = MO.getSubReg();
538 if (SubReg != 0) {
Matthias Braune6a24852015-09-25 21:51:14 +0000539 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
540 if ((LaneMask & SR.LaneMask) == 0)
Matthias Braun20e1f382014-12-10 01:12:18 +0000541 continue;
542 }
543 // We only need to visit each instruction once.
544 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
545 if (Idx == LastIdx)
546 continue;
547 LastIdx = Idx;
548
549 LiveQueryResult LRQ = SR.Query(Idx);
550 VNInfo *VNI = LRQ.valueIn();
551 // For Subranges it is possible that only undef values are left in that
552 // part of the subregister, so there is no real liverange at the use
553 if (!VNI)
554 continue;
555
556 // Special case: An early-clobber tied operand reads and writes the
557 // register one slot early.
558 if (VNInfo *DefVNI = LRQ.valueDefined())
559 Idx = DefVNI->def;
560
561 WorkList.push_back(std::make_pair(Idx, VNI));
562 }
563
564 // Create a new live ranges with only minimal live segments per def.
565 LiveRange NewLR;
566 createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
567 extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
568
Matthias Braun20e1f382014-12-10 01:12:18 +0000569 // Move the trimmed ranges back.
570 SR.segments.swap(NewLR.segments);
Matthias Braun15abf372014-12-18 19:58:52 +0000571
572 // Remove dead PHI value numbers
573 for (auto VNI : SR.valnos) {
574 if (VNI->isUnused())
575 continue;
576 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
577 assert(Segment != nullptr && "Missing segment for VNI");
578 if (Segment->end != VNI->def.getDeadSlot())
579 continue;
580 if (VNI->isPHIDef()) {
581 // This is a dead PHI. Remove it.
582 VNI->markUnused();
583 SR.removeSegment(*Segment);
584 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
585 }
586 }
587
Matthias Braun20e1f382014-12-10 01:12:18 +0000588 DEBUG(dbgs() << "Shrunk: " << SR << '\n');
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000589}
590
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000591void LiveIntervals::extendToIndices(LiveRange &LR,
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000592 ArrayRef<SlotIndex> Indices) {
593 assert(LRCalc && "LRCalc not initialized.");
594 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
595 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
Matthias Braun2d5c32b2013-10-10 21:28:57 +0000596 LRCalc->extend(LR, Indices[i]);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000597}
598
Matthias Braun8970d842014-12-10 01:12:36 +0000599void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000600 SmallVectorImpl<SlotIndex> *EndPoints) {
Matthias Braun8970d842014-12-10 01:12:36 +0000601 LiveQueryResult LRQ = LR.Query(Kill);
602 VNInfo *VNI = LRQ.valueOutOrDead();
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000603 if (!VNI)
604 return;
605
606 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
Matthias Braun8970d842014-12-10 01:12:36 +0000607 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000608
609 // If VNI isn't live out from KillMBB, the value is trivially pruned.
610 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun8970d842014-12-10 01:12:36 +0000611 LR.removeSegment(Kill, LRQ.endPoint());
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000612 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
613 return;
614 }
615
616 // VNI is live out of KillMBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000617 LR.removeSegment(Kill, MBBEnd);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000618 if (EndPoints) EndPoints->push_back(MBBEnd);
619
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000620 // Find all blocks that are reachable from KillMBB without leaving VNI's live
621 // range. It is possible that KillMBB itself is reachable, so start a DFS
622 // from each successor.
623 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
624 VisitedTy Visited;
625 for (MachineBasicBlock::succ_iterator
626 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
627 SuccI != SuccE; ++SuccI) {
628 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
629 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
630 I != E;) {
631 MachineBasicBlock *MBB = *I;
632
633 // Check if VNI is live in to MBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000634 SlotIndex MBBStart, MBBEnd;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000635 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
Matthias Braun8970d842014-12-10 01:12:36 +0000636 LiveQueryResult LRQ = LR.Query(MBBStart);
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000637 if (LRQ.valueIn() != VNI) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000638 // This block isn't part of the VNI segment. Prune the search.
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000639 I.skipChildren();
640 continue;
641 }
642
643 // Prune the search if VNI is killed in MBB.
644 if (LRQ.endPoint() < MBBEnd) {
Matthias Braun8970d842014-12-10 01:12:36 +0000645 LR.removeSegment(MBBStart, LRQ.endPoint());
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000646 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
647 I.skipChildren();
648 continue;
649 }
650
651 // VNI is live through MBB.
Matthias Braun8970d842014-12-10 01:12:36 +0000652 LR.removeSegment(MBBStart, MBBEnd);
Jakob Stoklund Olesen2f6dfc72012-10-13 16:15:31 +0000653 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000654 ++I;
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000655 }
Jakob Stoklund Olesen0bb3dd72012-09-17 23:03:25 +0000656 }
657}
Jakob Stoklund Olesen55fc1d02011-02-08 00:03:05 +0000658
Evan Chengbe51f282007-11-12 06:35:08 +0000659//===----------------------------------------------------------------------===//
660// Register allocator hooks.
661//
662
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000663void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
664 // Keep track of regunit ranges.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000665 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
Matthias Braun714c4942014-12-20 01:54:50 +0000666 // Keep track of subregister ranges.
667 SmallVector<std::pair<const LiveInterval::SubRange*,
668 LiveRange::const_iterator>, 4> SRs;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000669
Jakob Stoklund Olesen781e0b92012-06-20 23:23:59 +0000670 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
671 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000672 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000673 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000674 const LiveInterval &LI = getInterval(Reg);
675 if (LI.empty())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000676 continue;
677
678 // Find the regunit intervals for the assigned register. They may overlap
679 // the virtual register live range, cancelling any kills.
680 RU.clear();
681 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
682 ++Units) {
Matthias Braun7f8dece2014-12-20 01:54:48 +0000683 const LiveRange &RURange = getRegUnit(*Units);
684 if (RURange.empty())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000685 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000686 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000687 }
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000688
Matthias Brauna25e13a2015-03-19 00:21:58 +0000689 if (MRI->subRegLivenessEnabled()) {
Matthias Braun714c4942014-12-20 01:54:50 +0000690 SRs.clear();
691 for (const LiveInterval::SubRange &SR : LI.subranges()) {
692 SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
693 }
694 }
695
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000696 // Every instruction that kills Reg corresponds to a segment range end
697 // point.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000698 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000699 ++RI) {
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000700 // A block index indicates an MBB edge.
701 if (RI->end.isBlock())
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000702 continue;
703 MachineInstr *MI = getInstructionFromIndex(RI->end);
704 if (!MI)
705 continue;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000706
Matthias Braunc9d5c0f2013-10-04 16:52:58 +0000707 // Check if any of the regunits are live beyond the end of RI. That could
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000708 // happen when a physreg is defined as a copy of a virtreg:
709 //
710 // %EAX = COPY %vreg5
711 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
712 // BAR %EAX<kill>
713 //
714 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
Matthias Braun7f8dece2014-12-20 01:54:48 +0000715 for (auto &RUP : RU) {
716 const LiveRange &RURange = *RUP.first;
Matthias Braunf603c882014-12-24 02:11:43 +0000717 LiveRange::const_iterator &I = RUP.second;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000718 if (I == RURange.end())
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000719 continue;
Matthias Braun7f8dece2014-12-20 01:54:48 +0000720 I = RURange.advanceTo(I, RI->end);
721 if (I == RURange.end() || I->start >= RI->end)
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000722 continue;
723 // I is overlapping RI.
Matthias Braun714c4942014-12-20 01:54:50 +0000724 goto CancelKill;
Jakob Stoklund Olesenbb4bdd82012-09-06 18:15:18 +0000725 }
Matthias Braund70caaf2014-12-10 01:13:04 +0000726
Matthias Brauna25e13a2015-03-19 00:21:58 +0000727 if (MRI->subRegLivenessEnabled()) {
Matthias Braun714c4942014-12-20 01:54:50 +0000728 // When reading a partial undefined value we must not add a kill flag.
729 // The regalloc might have used the undef lane for something else.
730 // Example:
731 // %vreg1 = ... ; R32: %vreg1
732 // %vreg2:high16 = ... ; R64: %vreg2
733 // = read %vreg2<kill> ; R64: %vreg2
734 // = read %vreg1 ; R32: %vreg1
735 // The <kill> flag is correct for %vreg2, but the register allocator may
736 // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
737 // are actually never written by %vreg2. After assignment the <kill>
738 // flag at the read instruction is invalid.
Matthias Braune6a24852015-09-25 21:51:14 +0000739 LaneBitmask DefinedLanesMask;
Matthias Braun714c4942014-12-20 01:54:50 +0000740 if (!SRs.empty()) {
741 // Compute a mask of lanes that are defined.
742 DefinedLanesMask = 0;
743 for (auto &SRP : SRs) {
744 const LiveInterval::SubRange &SR = *SRP.first;
Matthias Braunf603c882014-12-24 02:11:43 +0000745 LiveRange::const_iterator &I = SRP.second;
Matthias Braun714c4942014-12-20 01:54:50 +0000746 if (I == SR.end())
747 continue;
748 I = SR.advanceTo(I, RI->end);
749 if (I == SR.end() || I->start >= RI->end)
750 continue;
751 // I is overlapping RI
752 DefinedLanesMask |= SR.LaneMask;
Matthias Braund70caaf2014-12-10 01:13:04 +0000753 }
Matthias Braun714c4942014-12-20 01:54:50 +0000754 } else
755 DefinedLanesMask = ~0u;
756
757 bool IsFullWrite = false;
758 for (const MachineOperand &MO : MI->operands()) {
759 if (!MO.isReg() || MO.getReg() != Reg)
760 continue;
761 if (MO.isUse()) {
762 // Reading any undefined lanes?
Matthias Braune6a24852015-09-25 21:51:14 +0000763 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
Matthias Braun714c4942014-12-20 01:54:50 +0000764 if ((UseMask & ~DefinedLanesMask) != 0)
765 goto CancelKill;
766 } else if (MO.getSubReg() == 0) {
767 // Writing to the full register?
768 assert(MO.isDef());
769 IsFullWrite = true;
770 }
771 }
772
773 // If an instruction writes to a subregister, a new segment starts in
774 // the LiveInterval. But as this is only overriding part of the register
775 // adding kill-flags is not correct here after registers have been
776 // assigned.
777 if (!IsFullWrite) {
778 // Next segment has to be adjacent in the subregister write case.
779 LiveRange::const_iterator N = std::next(RI);
780 if (N != LI.end() && N->start == RI->end)
781 goto CancelKill;
Matthias Braund70caaf2014-12-10 01:13:04 +0000782 }
783 }
784
Matthias Braun714c4942014-12-20 01:54:50 +0000785 MI->addRegisterKilled(Reg, nullptr);
786 continue;
787CancelKill:
788 MI->clearRegisterKills(Reg, nullptr);
Jakob Stoklund Olesenf2b16dc2011-02-08 21:13:03 +0000789 }
790 }
791}
792
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000793MachineBasicBlock*
794LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
795 // A local live range must be fully contained inside the block, meaning it is
796 // defined and killed at instructions, not at block boundaries. It is not
797 // live in or or out of any block.
798 //
799 // It is technically possible to have a PHI-defined live range identical to a
800 // single block, but we are going to return false in that case.
Lang Hames05fb9632009-11-03 23:52:08 +0000801
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000802 SlotIndex Start = LI.beginIndex();
803 if (Start.isBlock())
Craig Topperc0196b12014-04-14 00:51:57 +0000804 return nullptr;
Lang Hames05fb9632009-11-03 23:52:08 +0000805
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000806 SlotIndex Stop = LI.endIndex();
807 if (Stop.isBlock())
Craig Topperc0196b12014-04-14 00:51:57 +0000808 return nullptr;
Lang Hames05fb9632009-11-03 23:52:08 +0000809
Jakob Stoklund Olesenaa06de22012-02-10 01:23:55 +0000810 // getMBBFromIndex doesn't need to search the MBB table when both indexes
811 // belong to proper instructions.
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000812 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
813 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Craig Topperc0196b12014-04-14 00:51:57 +0000814 return MBB1 == MBB2 ? MBB1 : nullptr;
Evan Cheng8e223792007-11-17 00:40:40 +0000815}
816
Jakob Stoklund Olesen06d6a532012-08-03 20:10:24 +0000817bool
818LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
Matthias Braun96761952014-12-10 23:07:54 +0000819 for (const VNInfo *PHI : LI.valnos) {
Jakob Stoklund Olesen06d6a532012-08-03 20:10:24 +0000820 if (PHI->isUnused() || !PHI->isPHIDef())
821 continue;
822 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
823 // Conservatively return true instead of scanning huge predecessor lists.
824 if (PHIMBB->pred_size() > 100)
825 return true;
826 for (MachineBasicBlock::const_pred_iterator
827 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
828 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
829 return true;
830 }
831 return false;
832}
833
Jakob Stoklund Olesen115da882010-03-01 20:59:38 +0000834float
Michael Gottesman9f49d742013-12-14 00:53:32 +0000835LiveIntervals::getSpillWeight(bool isDef, bool isUse,
836 const MachineBlockFrequencyInfo *MBFI,
837 const MachineInstr *MI) {
838 BlockFrequency Freq = MBFI->getBlockFreq(MI->getParent());
Michael Gottesman5e985ee2013-12-14 02:37:38 +0000839 const float Scale = 1.0f / MBFI->getEntryFreq();
Michael Gottesman9f49d742013-12-14 00:53:32 +0000840 return (isDef + isUse) * (Freq.getFrequency() * Scale);
Jakob Stoklund Olesen115da882010-03-01 20:59:38 +0000841}
842
Matthias Braund7df9352013-10-10 21:28:47 +0000843LiveRange::Segment
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000844LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr* startInst) {
Mark Lacey9d8103d2013-08-14 23:50:16 +0000845 LiveInterval& Interval = createEmptyInterval(reg);
Owen Anderson35e2dfe2008-06-05 17:15:43 +0000846 VNInfo* VN = Interval.getNextValue(
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000847 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Jakob Stoklund Olesenad6b22e2012-02-04 05:20:49 +0000848 getVNInfoAllocator());
Matthias Braund7df9352013-10-10 21:28:47 +0000849 LiveRange::Segment S(
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000850 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Lang Hames4c052262009-12-22 00:11:50 +0000851 getMBBEndIdx(startInst->getParent()), VN);
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000852 Interval.addSegment(S);
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000853
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000854 return S;
Owen Anderson35e2dfe2008-06-05 17:15:43 +0000855}
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000856
857
858//===----------------------------------------------------------------------===//
859// Register mask functions
860//===----------------------------------------------------------------------===//
861
862bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
863 BitVector &UsableRegs) {
864 if (LI.empty())
865 return false;
Jakob Stoklund Olesen9ef50bd2012-02-10 01:31:31 +0000866 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
867
868 // Use a smaller arrays for local live ranges.
869 ArrayRef<SlotIndex> Slots;
870 ArrayRef<const uint32_t*> Bits;
871 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
872 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
873 Bits = getRegMaskBitsInBlock(MBB->getNumber());
874 } else {
875 Slots = getRegMaskSlots();
876 Bits = getRegMaskBits();
877 }
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000878
879 // We are going to enumerate all the register mask slots contained in LI.
880 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000881 ArrayRef<SlotIndex>::iterator SlotI =
882 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
883 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
884
885 // No slots in range, LI begins after the last call.
886 if (SlotI == SlotE)
887 return false;
888
889 bool Found = false;
890 for (;;) {
891 assert(*SlotI >= LiveI->start);
892 // Loop over all slots overlapping this segment.
893 while (*SlotI < LiveI->end) {
894 // *SlotI overlaps LI. Collect mask bits.
895 if (!Found) {
896 // This is the first overlap. Initialize UsableRegs to all ones.
897 UsableRegs.clear();
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +0000898 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000899 Found = true;
900 }
901 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9ef50bd2012-02-10 01:31:31 +0000902 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3ff74d82012-02-08 17:33:45 +0000903 if (++SlotI == SlotE)
904 return Found;
905 }
906 // *SlotI is beyond the current LI segment.
907 LiveI = LI.advanceTo(LiveI, *SlotI);
908 if (LiveI == LiveE)
909 return Found;
910 // Advance SlotI until it overlaps.
911 while (*SlotI < LiveI->start)
912 if (++SlotI == SlotE)
913 return Found;
914 }
915}
Lang Hamesb9057d52012-02-17 18:44:18 +0000916
917//===----------------------------------------------------------------------===//
918// IntervalUpdate class.
919//===----------------------------------------------------------------------===//
920
Lang Hames7e2ce882012-02-21 00:00:36 +0000921// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hamesb9057d52012-02-17 18:44:18 +0000922class LiveIntervals::HMEditor {
923private:
Lang Hames59761982012-02-17 23:43:40 +0000924 LiveIntervals& LIS;
925 const MachineRegisterInfo& MRI;
926 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000927 SlotIndex OldIdx;
Lang Hames59761982012-02-17 23:43:40 +0000928 SlotIndex NewIdx;
Matthias Braun34e1be92013-10-10 21:29:02 +0000929 SmallPtrSet<LiveRange*, 8> Updated;
Andrew Trickd9d4be02012-10-16 00:22:51 +0000930 bool UpdateFlags;
Lang Hames13b11522012-02-19 07:13:05 +0000931
Lang Hamesb9057d52012-02-17 18:44:18 +0000932public:
Lang Hames59761982012-02-17 23:43:40 +0000933 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000934 const TargetRegisterInfo& TRI,
Andrew Trickd9d4be02012-10-16 00:22:51 +0000935 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
936 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
937 UpdateFlags(UpdateFlags) {}
938
939 // FIXME: UpdateFlags is a workaround that creates live intervals for all
940 // physregs, even those that aren't needed for regalloc, in order to update
941 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
942 // flags, and postRA passes will use a live register utility instead.
Matthias Braun34e1be92013-10-10 21:29:02 +0000943 LiveRange *getRegUnitLI(unsigned Unit) {
Andrew Trickd9d4be02012-10-16 00:22:51 +0000944 if (UpdateFlags)
945 return &LIS.getRegUnit(Unit);
946 return LIS.getCachedRegUnit(Unit);
947 }
Lang Hamesb9057d52012-02-17 18:44:18 +0000948
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000949 /// Update all live ranges touched by MI, assuming a move from OldIdx to
950 /// NewIdx.
951 void updateAllRanges(MachineInstr *MI) {
952 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
953 bool hasRegMask = false;
Matthias Braune41e1462015-05-29 02:56:46 +0000954 for (MachineOperand &MO : MI->operands()) {
955 if (MO.isRegMask())
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000956 hasRegMask = true;
Matthias Braune41e1462015-05-29 02:56:46 +0000957 if (!MO.isReg())
Lang Hamesd6e765c2012-02-21 22:29:38 +0000958 continue;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000959 // Aggressively clear all kill flags.
960 // They are reinserted by VirtRegRewriter.
Matthias Braune41e1462015-05-29 02:56:46 +0000961 if (MO.isUse())
962 MO.setIsKill(false);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000963
Matthias Braune41e1462015-05-29 02:56:46 +0000964 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000965 if (!Reg)
966 continue;
967 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun34e1be92013-10-10 21:29:02 +0000968 LiveInterval &LI = LIS.getInterval(Reg);
Matthias Braun7044d692014-12-10 01:12:20 +0000969 if (LI.hasSubRanges()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000970 unsigned SubReg = MO.getSubReg();
Matthias Braune6a24852015-09-25 21:51:14 +0000971 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
Matthias Braun09afa1e2014-12-11 00:59:06 +0000972 for (LiveInterval::SubRange &S : LI.subranges()) {
973 if ((S.LaneMask & LaneMask) == 0)
Matthias Braun7044d692014-12-10 01:12:20 +0000974 continue;
Matthias Braun09afa1e2014-12-11 00:59:06 +0000975 updateRange(S, Reg, S.LaneMask);
Matthias Braun7044d692014-12-10 01:12:20 +0000976 }
977 }
978 updateRange(LI, Reg, 0);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000979 continue;
980 }
981
982 // For physregs, only update the regunits that actually have a
983 // precomputed live range.
984 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Matthias Braun34e1be92013-10-10 21:29:02 +0000985 if (LiveRange *LR = getRegUnitLI(*Units))
Matthias Braun7044d692014-12-10 01:12:20 +0000986 updateRange(*LR, *Units, 0);
Lang Hamesd6e765c2012-02-21 22:29:38 +0000987 }
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000988 if (hasRegMask)
989 updateRegMaskSlots();
Lang Hames13b11522012-02-19 07:13:05 +0000990 }
991
Lang Hames4645a722012-02-19 03:00:30 +0000992private:
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000993 /// Update a single live range, assuming an instruction has been moved from
994 /// OldIdx to NewIdx.
Matthias Braune6a24852015-09-25 21:51:14 +0000995 void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
David Blaikie70573dc2014-11-19 07:49:26 +0000996 if (!Updated.insert(&LR).second)
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +0000997 return;
998 DEBUG({
999 dbgs() << " ";
Matthias Braun7044d692014-12-10 01:12:20 +00001000 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001001 dbgs() << PrintReg(Reg);
Matthias Braun7044d692014-12-10 01:12:20 +00001002 if (LaneMask != 0)
Matthias Braunc804cdb2015-09-25 21:51:24 +00001003 dbgs() << " L" << PrintLaneMask(LaneMask);
Matthias Braun7044d692014-12-10 01:12:20 +00001004 } else {
Matthias Braun34e1be92013-10-10 21:29:02 +00001005 dbgs() << PrintRegUnit(Reg, &TRI);
Matthias Braun7044d692014-12-10 01:12:20 +00001006 }
Matthias Braun34e1be92013-10-10 21:29:02 +00001007 dbgs() << ":\t" << LR << '\n';
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001008 });
1009 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
Matthias Braun34e1be92013-10-10 21:29:02 +00001010 handleMoveDown(LR);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001011 else
Matthias Braun7044d692014-12-10 01:12:20 +00001012 handleMoveUp(LR, Reg, LaneMask);
Matthias Braun34e1be92013-10-10 21:29:02 +00001013 DEBUG(dbgs() << " -->\t" << LR << '\n');
1014 LR.verify();
Lang Hamesb9057d52012-02-17 18:44:18 +00001015 }
1016
Matthias Braun34e1be92013-10-10 21:29:02 +00001017 /// Update LR to reflect an instruction has been moved downwards from OldIdx
Matthias Braun242b8bb2016-01-26 00:43:50 +00001018 /// to NewIdx (OldIdx < NewIdx).
Matthias Braun34e1be92013-10-10 21:29:02 +00001019 void handleMoveDown(LiveRange &LR) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001020 LiveRange::iterator E = LR.end();
Matthias Braun242b8bb2016-01-26 00:43:50 +00001021 // Segment going into OldIdx.
1022 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1023
1024 // No value live before or after OldIdx? Nothing to do.
1025 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001026 return;
Lang Hames13b11522012-02-19 07:13:05 +00001027
Matthias Braun242b8bb2016-01-26 00:43:50 +00001028 LiveRange::iterator OldIdxOut;
1029 // Do we have a value live-in to OldIdx?
1030 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001031 // If the live-in value already extends to NewIdx, there is nothing to do.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001032 if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001033 return;
1034 // Aggressively remove all kill flags from the old kill point.
1035 // Kill flags shouldn't be used while live intervals exist, they will be
1036 // reinserted by VirtRegRewriter.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001037 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001038 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1039 if (MO->isReg() && MO->isUse())
1040 MO->setIsKill(false);
Matthias Braun4a6c7282016-02-15 19:25:36 +00001041
1042 // Is there a def before NewIdx which is not OldIdx?
1043 LiveRange::iterator Next = std::next(OldIdxIn);
1044 if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1045 SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1046 // If we are here then OldIdx was just a use but not a def. We only have
1047 // to ensure liveness extends to NewIdx.
1048 LiveRange::iterator NewIdxIn =
1049 LR.advanceTo(Next, NewIdx.getBaseIndex());
1050 // Extend the segment before NewIdx if necessary.
1051 if (NewIdxIn == E ||
1052 !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1053 LiveRange::iterator Prev = std::prev(NewIdxIn);
1054 Prev->end = NewIdx.getRegSlot();
1055 }
1056 return;
1057 }
1058
Matthias Braun242b8bb2016-01-26 00:43:50 +00001059 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
Matthias Braundb320772016-01-26 01:40:48 +00001060 // invalid by overlapping ranges.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001061 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1062 OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1063 // If this was not a kill, then there was no def and we're done.
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001064 if (!isKill)
1065 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001066
1067 // Did we have a Def at OldIdx?
Matthias Braun4a6c7282016-02-15 19:25:36 +00001068 OldIdxOut = Next;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001069 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1070 return;
1071 } else {
1072 OldIdxOut = OldIdxIn;
Lang Hames13b11522012-02-19 07:13:05 +00001073 }
1074
Matthias Braun242b8bb2016-01-26 00:43:50 +00001075 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1076 // to the segment starting there.
1077 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1078 "No def?");
1079 VNInfo *OldIdxVNI = OldIdxOut->valno;
1080 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1081
1082 // If the defined value extends beyond NewIdx, just move the beginning
1083 // of the segment to NewIdx.
1084 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1085 if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1086 OldIdxVNI->def = NewIdxDef;
1087 OldIdxOut->start = OldIdxVNI->def;
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001088 return;
1089 }
Matthias Braun242b8bb2016-01-26 00:43:50 +00001090
1091 // If we are here then we have a Definition at OldIdx which ends before
Matthias Braun4a6c7282016-02-15 19:25:36 +00001092 // NewIdx.
1093
Matthias Braun242b8bb2016-01-26 00:43:50 +00001094 // Is there an existing Def at NewIdx?
1095 LiveRange::iterator AfterNewIdx
1096 = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
Matthias Braun4a6c7282016-02-15 19:25:36 +00001097 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1098 if (!OldIdxDefIsDead &&
1099 SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1100 // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1101 VNInfo *DefVNI;
1102 if (OldIdxOut != LR.begin() &&
1103 !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1104 OldIdxOut->start)) {
1105 // There is no gap between OldIdxOut and its predecessor anymore,
1106 // merge them.
1107 LiveRange::iterator IPrev = std::prev(OldIdxOut);
1108 DefVNI = OldIdxVNI;
1109 IPrev->end = OldIdxOut->end;
1110 } else {
1111 // The value is live in to OldIdx
1112 LiveRange::iterator INext = std::next(OldIdxOut);
1113 assert(INext != E && "Must have following segment");
1114 // We merge OldIdxOut and its successor. As we're dealing with subreg
1115 // reordering, there is always a successor to OldIdxOut in the same BB
1116 // We don't need INext->valno anymore and will reuse for the new segment
1117 // we create later.
1118 DefVNI = INext->valno;
1119 INext->start = OldIdxOut->end;
1120 INext->valno = OldIdxVNI;
1121 INext->valno->def = INext->start;
1122 }
1123 // If NewIdx is behind the last segment, extend that and append a new one.
1124 if (AfterNewIdx == E) {
1125 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1126 // one position.
1127 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1128 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1129 std::copy(std::next(OldIdxOut), E, OldIdxOut);
1130 // The last segment is undefined now, reuse it for a dead def.
1131 LiveRange::iterator NewSegment = std::prev(E);
1132 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1133 DefVNI);
1134 DefVNI->def = NewIdxDef;
1135
1136 LiveRange::iterator Prev = std::prev(NewSegment);
1137 Prev->end = NewIdxDef;
1138 } else {
1139 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1140 // one position.
1141 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1142 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1143 std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1144 LiveRange::iterator Prev = std::prev(AfterNewIdx);
1145 // We have two cases:
1146 if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1147 // Case 1: NewIdx is inside a liverange. Split this liverange at
1148 // NewIdxDef into the segment "Prev" followed by "NewSegment".
1149 LiveRange::iterator NewSegment = AfterNewIdx;
1150 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1151 Prev->valno->def = NewIdxDef;
1152
1153 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1154 DefVNI->def = Prev->start;
1155 } else {
1156 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1157 // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1158 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1159 DefVNI->def = NewIdxDef;
1160 assert(DefVNI != AfterNewIdx->valno);
1161 }
1162 }
1163 return;
1164 }
1165
Matthias Braun242b8bb2016-01-26 00:43:50 +00001166 if (AfterNewIdx != E &&
1167 SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1168 // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1169 // that value.
1170 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1171 LR.removeValNo(OldIdxVNI);
1172 } else {
1173 // There was no existing def at NewIdx. We need to create a dead def
1174 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1175 // a new segment at the place where we want to construct the dead def.
1176 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1177 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1178 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1179 std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1180 // We can reuse OldIdxVNI now.
1181 LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1182 VNInfo *NewSegmentVNI = OldIdxVNI;
1183 NewSegmentVNI->def = NewIdxDef;
1184 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1185 NewSegmentVNI);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001186 }
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001187 }
1188
Matthias Braun34e1be92013-10-10 21:29:02 +00001189 /// Update LR to reflect an instruction has been moved upwards from OldIdx
Matthias Braun242b8bb2016-01-26 00:43:50 +00001190 /// to NewIdx (NewIdx < OldIdx).
Matthias Braune6a24852015-09-25 21:51:14 +00001191 void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001192 LiveRange::iterator E = LR.end();
Matthias Braun242b8bb2016-01-26 00:43:50 +00001193 // Segment going into OldIdx.
1194 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1195
1196 // No value live before or after OldIdx? Nothing to do.
1197 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001198 return;
1199
Matthias Braun242b8bb2016-01-26 00:43:50 +00001200 LiveRange::iterator OldIdxOut;
1201 // Do we have a value live-in to OldIdx?
1202 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1203 // If the live-in value isn't killed here, then we have no Def at
1204 // OldIdx, moreover the value must be live at NewIdx so there is nothing
1205 // to do.
1206 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1207 if (!isKill)
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001208 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001209
1210 // At this point we have to move OldIdxIn->end back to the nearest
Matthias Braun4a6c7282016-02-15 19:25:36 +00001211 // previous use or (dead-)def but no further than NewIdx.
1212 SlotIndex DefBeforeOldIdx
1213 = std::max(OldIdxIn->start.getDeadSlot(),
1214 NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1215 OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
Matthias Braun242b8bb2016-01-26 00:43:50 +00001216
Matthias Braun4a6c7282016-02-15 19:25:36 +00001217 // Did we have a Def at OldIdx? If not we are done now.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001218 OldIdxOut = std::next(OldIdxIn);
Matthias Braun4a6c7282016-02-15 19:25:36 +00001219 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001220 return;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001221 } else {
1222 OldIdxOut = OldIdxIn;
Matthias Braun4a6c7282016-02-15 19:25:36 +00001223 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
Matthias Braun242b8bb2016-01-26 00:43:50 +00001224 }
1225
1226 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1227 // to the segment starting there.
1228 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1229 "No def?");
1230 VNInfo *OldIdxVNI = OldIdxOut->valno;
1231 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1232 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1233
1234 // Is there an existing def at NewIdx?
1235 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1236 LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1237 if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1238 assert(NewIdxOut->valno != OldIdxVNI &&
1239 "Same value defined more than once?");
1240 // If OldIdx was a dead def remove it.
1241 if (!OldIdxDefIsDead) {
Matthias Braundb320772016-01-26 01:40:48 +00001242 // Remove segment starting at NewIdx and move begin of OldIdxOut to
1243 // NewIdx so it can take its place.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001244 OldIdxVNI->def = NewIdxDef;
1245 OldIdxOut->start = NewIdxDef;
1246 LR.removeValNo(NewIdxOut->valno);
1247 } else {
Matthias Braundb320772016-01-26 01:40:48 +00001248 // Simply remove the dead def at OldIdx.
Matthias Braun242b8bb2016-01-26 00:43:50 +00001249 LR.removeValNo(OldIdxVNI);
1250 }
1251 } else {
1252 // Previously nothing was live after NewIdx, so all we have to do now is
1253 // move the begin of OldIdxOut to NewIdx.
1254 if (!OldIdxDefIsDead) {
Matthias Braun4a6c7282016-02-15 19:25:36 +00001255 // Do we have any intermediate Defs between OldIdx and NewIdx?
1256 if (OldIdxIn != E &&
1257 SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1258 // OldIdx is not a dead def and NewIdx is before predecessor start.
1259 LiveRange::iterator NewIdxIn = NewIdxOut;
1260 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1261 const SlotIndex SplitPos = NewIdxDef;
1262
1263 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1264 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1265 OldIdxIn->valno);
1266 // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1267 // We Slide [NewIdxIn, OldIdxIn) down one position.
1268 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1269 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1270 std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1271 // NewIdxIn is now considered undef so we can reuse it for the moved
1272 // value.
1273 LiveRange::iterator NewSegment = NewIdxIn;
1274 LiveRange::iterator Next = std::next(NewSegment);
1275 NewSegment->valno = OldIdxVNI;
1276 if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1277 // There is no gap between NewSegment and its predecessor.
1278 *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1279 NewSegment->valno);
1280 NewSegment->valno->def = Next->start;
1281
1282 *Next = LiveRange::Segment(SplitPos, Next->end, Next->valno);
1283 Next->valno->def = SplitPos;
1284 } else {
1285 // There is a gap between NewSegment and its predecessor
1286 // Value becomes live in.
1287 *NewSegment = LiveRange::Segment(SplitPos, Next->start,
1288 NewSegment->valno);
1289 NewSegment->valno->def = SplitPos;
1290 }
1291 } else {
1292 // Leave the end point of a live def.
1293 OldIdxOut->start = NewIdxDef;
1294 OldIdxVNI->def = NewIdxDef;
1295 if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1296 OldIdxIn->end = NewIdx.getRegSlot();
1297 }
Matthias Braun242b8bb2016-01-26 00:43:50 +00001298 } else {
1299 // OldIdxVNI is a dead def. It may have been moved across other values
1300 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1301 // down one position.
1302 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1303 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1304 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1305 // OldIdxVNI can be reused now to build a new dead def segment.
1306 LiveRange::iterator NewSegment = NewIdxOut;
1307 VNInfo *NewSegmentVNI = OldIdxVNI;
1308 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1309 NewSegmentVNI);
1310 NewSegmentVNI->def = NewIdxDef;
Lang Hames13b11522012-02-19 07:13:05 +00001311 }
1312 }
Lang Hames13b11522012-02-19 07:13:05 +00001313 }
1314
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001315 void updateRegMaskSlots() {
Lang Hames59761982012-02-17 23:43:40 +00001316 SmallVectorImpl<SlotIndex>::iterator RI =
1317 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1318 OldIdx);
Jakob Stoklund Olesen13d55622012-11-09 19:18:49 +00001319 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1320 "No RegMask at OldIdx.");
1321 *RI = NewIdx.getRegSlot();
1322 assert((RI == LIS.RegMaskSlots.begin() ||
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001323 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1324 "Cannot move regmask instruction above another call");
1325 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1326 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1327 "Cannot move regmask instruction below another call");
Lang Hamesa9afc6a2012-02-17 21:29:41 +00001328 }
Lang Hames4645a722012-02-19 03:00:30 +00001329
1330 // Return the last use of reg between NewIdx and OldIdx.
Matthias Braun4a6c7282016-02-15 19:25:36 +00001331 SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1332 LaneBitmask LaneMask) {
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001333 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braun4a6c7282016-02-15 19:25:36 +00001334 SlotIndex LastUse = Before;
Matthias Braun7044d692014-12-10 01:12:20 +00001335 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1336 unsigned SubReg = MO.getSubReg();
1337 if (SubReg != 0 && LaneMask != 0
1338 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask) == 0)
1339 continue;
1340
1341 const MachineInstr *MI = MO.getParent();
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001342 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1343 if (InstSlot > LastUse && InstSlot < OldIdx)
Matthias Braun4a6c7282016-02-15 19:25:36 +00001344 LastUse = InstSlot.getRegSlot();
Lang Hamesc3d9a3d2012-09-12 06:56:16 +00001345 }
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001346 return LastUse;
Lang Hames4645a722012-02-19 03:00:30 +00001347 }
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001348
1349 // This is a regunit interval, so scanning the use list could be very
1350 // expensive. Scan upwards from OldIdx instead.
Matthias Braun4a6c7282016-02-15 19:25:36 +00001351 assert(Before < OldIdx && "Expected upwards move");
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001352 SlotIndexes *Indexes = LIS.getSlotIndexes();
Matthias Braun4a6c7282016-02-15 19:25:36 +00001353 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001354
1355 // OldIdx may not correspond to an instruction any longer, so set MII to
1356 // point to the next instruction after OldIdx, or MBB->end().
1357 MachineBasicBlock::iterator MII = MBB->end();
1358 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1359 Indexes->getNextNonNullIndex(OldIdx)))
1360 if (MI->getParent() == MBB)
1361 MII = MI;
1362
1363 MachineBasicBlock::iterator Begin = MBB->begin();
1364 while (MII != Begin) {
1365 if ((--MII)->isDebugValue())
1366 continue;
1367 SlotIndex Idx = Indexes->getInstructionIndex(MII);
1368
Matthias Braun4a6c7282016-02-15 19:25:36 +00001369 // Stop searching when Before is reached.
1370 if (!SlotIndex::isEarlierInstr(Before, Idx))
1371 return Before;
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001372
1373 // Check if MII uses Reg.
1374 for (MIBundleOperands MO(MII); MO.isValid(); ++MO)
1375 if (MO->isReg() &&
1376 TargetRegisterInfo::isPhysicalRegister(MO->getReg()) &&
1377 TRI.hasRegUnit(MO->getReg(), Reg))
Matthias Braun4a6c7282016-02-15 19:25:36 +00001378 return Idx.getRegSlot();
Jakob Stoklund Olesen8d1aaf22013-03-08 18:08:57 +00001379 }
Matthias Braun4a6c7282016-02-15 19:25:36 +00001380 // Didn't reach Before. It must be the first instruction in the block.
1381 return Before;
Lang Hames4645a722012-02-19 03:00:30 +00001382 }
Lang Hamesb9057d52012-02-17 18:44:18 +00001383};
1384
Andrew Trickd9d4be02012-10-16 00:22:51 +00001385void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001386 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +00001387 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1388 Indexes->removeMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001389 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
Lang Hames59761982012-02-17 23:43:40 +00001390 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1391 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hamesb9057d52012-02-17 18:44:18 +00001392 "Cannot handle moves across basic block boundaries.");
Lang Hamesb9057d52012-02-17 18:44:18 +00001393
Andrew Trickd9d4be02012-10-16 00:22:51 +00001394 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001395 HME.updateAllRanges(MI);
Lang Hamesd6e765c2012-02-21 22:29:38 +00001396}
1397
Jakob Stoklund Olesen2db11252012-06-19 22:50:53 +00001398void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trickd9d4be02012-10-16 00:22:51 +00001399 MachineInstr* BundleStart,
1400 bool UpdateFlags) {
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001401 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesen11fb2482012-06-04 22:39:14 +00001402 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
Andrew Trickd9d4be02012-10-16 00:22:51 +00001403 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesen1a87a292012-10-12 21:31:57 +00001404 HME.updateAllRanges(MI);
Lang Hamesb9057d52012-02-17 18:44:18 +00001405}
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001406
Matthias Braune5f861b2014-12-10 01:12:26 +00001407void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1408 const MachineBasicBlock::iterator End,
1409 const SlotIndex endIdx,
1410 LiveRange &LR, const unsigned Reg,
Matthias Braune6a24852015-09-25 21:51:14 +00001411 LaneBitmask LaneMask) {
Matthias Braune5f861b2014-12-10 01:12:26 +00001412 LiveInterval::iterator LII = LR.find(endIdx);
1413 SlotIndex lastUseIdx;
1414 if (LII != LR.end() && LII->start < endIdx)
1415 lastUseIdx = LII->end;
1416 else
1417 --LII;
1418
1419 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1420 --I;
1421 MachineInstr *MI = I;
1422 if (MI->isDebugValue())
1423 continue;
1424
1425 SlotIndex instrIdx = getInstructionIndex(MI);
1426 bool isStartValid = getInstructionFromIndex(LII->start);
1427 bool isEndValid = getInstructionFromIndex(LII->end);
1428
1429 // FIXME: This doesn't currently handle early-clobber or multiple removed
1430 // defs inside of the region to repair.
1431 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
1432 OE = MI->operands_end(); OI != OE; ++OI) {
1433 const MachineOperand &MO = *OI;
1434 if (!MO.isReg() || MO.getReg() != Reg)
1435 continue;
1436
1437 unsigned SubReg = MO.getSubReg();
Matthias Braune6a24852015-09-25 21:51:14 +00001438 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
Matthias Braune5f861b2014-12-10 01:12:26 +00001439 if ((Mask & LaneMask) == 0)
1440 continue;
1441
1442 if (MO.isDef()) {
1443 if (!isStartValid) {
1444 if (LII->end.isDead()) {
1445 SlotIndex prevStart;
1446 if (LII != LR.begin())
1447 prevStart = std::prev(LII)->start;
1448
1449 // FIXME: This could be more efficient if there was a
1450 // removeSegment method that returned an iterator.
1451 LR.removeSegment(*LII, true);
1452 if (prevStart.isValid())
1453 LII = LR.find(prevStart);
1454 else
1455 LII = LR.begin();
1456 } else {
1457 LII->start = instrIdx.getRegSlot();
1458 LII->valno->def = instrIdx.getRegSlot();
1459 if (MO.getSubReg() && !MO.isUndef())
1460 lastUseIdx = instrIdx.getRegSlot();
1461 else
1462 lastUseIdx = SlotIndex();
1463 continue;
1464 }
1465 }
1466
1467 if (!lastUseIdx.isValid()) {
1468 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1469 LiveRange::Segment S(instrIdx.getRegSlot(),
1470 instrIdx.getDeadSlot(), VNI);
1471 LII = LR.addSegment(S);
1472 } else if (LII->start != instrIdx.getRegSlot()) {
1473 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1474 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1475 LII = LR.addSegment(S);
1476 }
1477
1478 if (MO.getSubReg() && !MO.isUndef())
1479 lastUseIdx = instrIdx.getRegSlot();
1480 else
1481 lastUseIdx = SlotIndex();
1482 } else if (MO.isUse()) {
1483 // FIXME: This should probably be handled outside of this branch,
1484 // either as part of the def case (for defs inside of the region) or
1485 // after the loop over the region.
1486 if (!isEndValid && !LII->end.isBlock())
1487 LII->end = instrIdx.getRegSlot();
1488 if (!lastUseIdx.isValid())
1489 lastUseIdx = instrIdx.getRegSlot();
1490 }
1491 }
1492 }
1493}
1494
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001495void
1496LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
Cameron Zwarich24955962013-02-17 11:09:00 +00001497 MachineBasicBlock::iterator Begin,
1498 MachineBasicBlock::iterator End,
Cameron Zwarich1286ef92013-02-17 03:48:23 +00001499 ArrayRef<unsigned> OrigRegs) {
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001500 // Find anchor points, which are at the beginning/end of blocks or at
1501 // instructions that already have indexes.
1502 while (Begin != MBB->begin() && !Indexes->hasIndex(Begin))
1503 --Begin;
1504 while (End != MBB->end() && !Indexes->hasIndex(End))
1505 ++End;
1506
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001507 SlotIndex endIdx;
1508 if (End == MBB->end())
1509 endIdx = getMBBEndIdx(MBB).getPrevSlot();
Cameron Zwarich24955962013-02-17 11:09:00 +00001510 else
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001511 endIdx = getInstructionIndex(End);
Cameron Zwarich24955962013-02-17 11:09:00 +00001512
Cameron Zwarich29414822013-02-20 06:46:41 +00001513 Indexes->repairIndexesInRange(MBB, Begin, End);
1514
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001515 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1516 --I;
1517 MachineInstr *MI = I;
Cameron Zwarich63acc732013-02-23 10:25:25 +00001518 if (MI->isDebugValue())
1519 continue;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001520 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1521 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1522 if (MOI->isReg() &&
1523 TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1524 !hasInterval(MOI->getReg())) {
Mark Lacey9d8103d2013-08-14 23:50:16 +00001525 createAndComputeVirtRegInterval(MOI->getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001526 }
1527 }
1528 }
1529
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001530 for (unsigned i = 0, e = OrigRegs.size(); i != e; ++i) {
1531 unsigned Reg = OrigRegs[i];
1532 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1533 continue;
1534
1535 LiveInterval &LI = getInterval(Reg);
Cameron Zwarich8e7dc062013-02-20 22:09:57 +00001536 // FIXME: Should we support undefs that gain defs?
1537 if (!LI.hasAtLeastOneValue())
1538 continue;
1539
Matthias Braun09afa1e2014-12-11 00:59:06 +00001540 for (LiveInterval::SubRange &S : LI.subranges()) {
1541 repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001542 }
Matthias Braune5f861b2014-12-10 01:12:26 +00001543 repairOldRegInRange(Begin, End, endIdx, LI, Reg);
Cameron Zwarichbfebb412013-02-17 00:10:44 +00001544 }
1545}
Matthias Brauncfb8ad22015-01-21 18:50:21 +00001546
1547void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
1548 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1549 if (LiveRange *LR = getCachedRegUnit(*Units))
1550 if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1551 LR->removeValNo(VNI);
1552 }
1553}
Matthias Braun311730a2015-01-21 19:02:30 +00001554
1555void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
1556 VNInfo *VNI = LI.getVNInfoAt(Pos);
1557 if (VNI == nullptr)
1558 return;
1559 LI.removeValNo(VNI);
1560
1561 // Also remove the value in subranges.
1562 for (LiveInterval::SubRange &S : LI.subranges()) {
1563 if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1564 S.removeValNo(SVNI);
1565 }
1566 LI.removeEmptySubRanges();
1567}
Matthias Braund3dd1352015-09-22 03:44:41 +00001568
1569void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
1570 SmallVectorImpl<LiveInterval*> &SplitLIs) {
1571 ConnectedVNInfoEqClasses ConEQ(*this);
Matthias Braunbf47f632016-01-08 01:16:35 +00001572 unsigned NumComp = ConEQ.Classify(LI);
Matthias Braund3dd1352015-09-22 03:44:41 +00001573 if (NumComp <= 1)
1574 return;
1575 DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1576 unsigned Reg = LI.reg;
1577 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1578 for (unsigned I = 1; I < NumComp; ++I) {
1579 unsigned NewVReg = MRI->createVirtualRegister(RegClass);
1580 LiveInterval &NewLI = createEmptyInterval(NewVReg);
1581 SplitLIs.push_back(&NewLI);
1582 }
1583 ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1584}
Matthias Braun3907fde2016-01-20 00:23:21 +00001585
1586void LiveIntervals::renameDisconnectedComponents() {
1587 ConnectedSubRegClasses SubRegClasses(*this, *MRI);
1588
1589 // Iterate over all vregs. Note that we query getNumVirtRegs() the newly
1590 // created vregs end up with higher numbers but do not need to be visited as
1591 // there can't be any further splitting.
1592 for (size_t I = 0, E = MRI->getNumVirtRegs(); I < E; ++I) {
1593 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
1594 LiveInterval *LI = VirtRegIntervals[Reg];
1595 if (LI == nullptr || !LI->hasSubRanges())
1596 continue;
1597
1598 SubRegClasses.renameComponents(*LI);
1599 }
1600}