15db84df7SEugene Zelenko //===- LiveRegMatrix.cpp - Track register interference --------------------===//
2c26fbbfbSJakob Stoklund Olesen //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c26fbbfbSJakob Stoklund Olesen //
7c26fbbfbSJakob Stoklund Olesen //===----------------------------------------------------------------------===//
8c26fbbfbSJakob Stoklund Olesen //
9c26fbbfbSJakob Stoklund Olesen // This file defines the LiveRegMatrix analysis pass.
10c26fbbfbSJakob Stoklund Olesen //
11c26fbbfbSJakob Stoklund Olesen //===----------------------------------------------------------------------===//
12c26fbbfbSJakob Stoklund Olesen 
136bda14b3SChandler Carruth #include "llvm/CodeGen/LiveRegMatrix.h"
14866908c4SJakob Stoklund Olesen #include "RegisterCoalescer.h"
15c26fbbfbSJakob Stoklund Olesen #include "llvm/ADT/Statistic.h"
165db84df7SEugene Zelenko #include "llvm/CodeGen/LiveInterval.h"
175db84df7SEugene Zelenko #include "llvm/CodeGen/LiveIntervalUnion.h"
18f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
195db84df7SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
20b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
21b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
226bda14b3SChandler Carruth #include "llvm/CodeGen/VirtRegMap.h"
2305da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
245db84df7SEugene Zelenko #include "llvm/MC/LaneBitmask.h"
255db84df7SEugene Zelenko #include "llvm/MC/MCRegisterInfo.h"
266bda14b3SChandler Carruth #include "llvm/Pass.h"
27c26fbbfbSJakob Stoklund Olesen #include "llvm/Support/Debug.h"
28d9903888SChandler Carruth #include "llvm/Support/raw_ostream.h"
295db84df7SEugene Zelenko #include <cassert>
30c26fbbfbSJakob Stoklund Olesen 
31c26fbbfbSJakob Stoklund Olesen using namespace llvm;
32c26fbbfbSJakob Stoklund Olesen 
331b9dde08SChandler Carruth #define DEBUG_TYPE "regalloc"
341b9dde08SChandler Carruth 
35c26fbbfbSJakob Stoklund Olesen STATISTIC(NumAssigned   , "Number of registers assigned");
36c26fbbfbSJakob Stoklund Olesen STATISTIC(NumUnassigned , "Number of registers unassigned");
37c26fbbfbSJakob Stoklund Olesen 
38c26fbbfbSJakob Stoklund Olesen char LiveRegMatrix::ID = 0;
39c26fbbfbSJakob Stoklund Olesen INITIALIZE_PASS_BEGIN(LiveRegMatrix, "liveregmatrix",
40c26fbbfbSJakob Stoklund Olesen                       "Live Register Matrix", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)41c26fbbfbSJakob Stoklund Olesen INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
42c26fbbfbSJakob Stoklund Olesen INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
43c26fbbfbSJakob Stoklund Olesen INITIALIZE_PASS_END(LiveRegMatrix, "liveregmatrix",
44c26fbbfbSJakob Stoklund Olesen                     "Live Register Matrix", false, false)
45c26fbbfbSJakob Stoklund Olesen 
465db84df7SEugene Zelenko LiveRegMatrix::LiveRegMatrix() : MachineFunctionPass(ID) {}
47c26fbbfbSJakob Stoklund Olesen 
getAnalysisUsage(AnalysisUsage & AU) const48c26fbbfbSJakob Stoklund Olesen void LiveRegMatrix::getAnalysisUsage(AnalysisUsage &AU) const {
49c26fbbfbSJakob Stoklund Olesen   AU.setPreservesAll();
50c26fbbfbSJakob Stoklund Olesen   AU.addRequiredTransitive<LiveIntervals>();
51c26fbbfbSJakob Stoklund Olesen   AU.addRequiredTransitive<VirtRegMap>();
52c26fbbfbSJakob Stoklund Olesen   MachineFunctionPass::getAnalysisUsage(AU);
53c26fbbfbSJakob Stoklund Olesen }
54c26fbbfbSJakob Stoklund Olesen 
runOnMachineFunction(MachineFunction & MF)55c26fbbfbSJakob Stoklund Olesen bool LiveRegMatrix::runOnMachineFunction(MachineFunction &MF) {
56fc6de428SEric Christopher   TRI = MF.getSubtarget().getRegisterInfo();
57c26fbbfbSJakob Stoklund Olesen   LIS = &getAnalysis<LiveIntervals>();
58c26fbbfbSJakob Stoklund Olesen   VRM = &getAnalysis<VirtRegMap>();
59c26fbbfbSJakob Stoklund Olesen 
60c26fbbfbSJakob Stoklund Olesen   unsigned NumRegUnits = TRI->getNumRegUnits();
61c26fbbfbSJakob Stoklund Olesen   if (NumRegUnits != Matrix.size())
62c26fbbfbSJakob Stoklund Olesen     Queries.reset(new LiveIntervalUnion::Query[NumRegUnits]);
63c26fbbfbSJakob Stoklund Olesen   Matrix.init(LIUAlloc, NumRegUnits);
64c26fbbfbSJakob Stoklund Olesen 
65c26fbbfbSJakob Stoklund Olesen   // Make sure no stale queries get reused.
66c26fbbfbSJakob Stoklund Olesen   invalidateVirtRegs();
67c26fbbfbSJakob Stoklund Olesen   return false;
68c26fbbfbSJakob Stoklund Olesen }
69c26fbbfbSJakob Stoklund Olesen 
releaseMemory()70c26fbbfbSJakob Stoklund Olesen void LiveRegMatrix::releaseMemory() {
71c26fbbfbSJakob Stoklund Olesen   for (unsigned i = 0, e = Matrix.size(); i != e; ++i) {
72c26fbbfbSJakob Stoklund Olesen     Matrix[i].clear();
7312ae04bdSPuyan Lotfi     // No need to clear Queries here, since LiveIntervalUnion::Query doesn't
7412ae04bdSPuyan Lotfi     // have anything important to clear and LiveRegMatrix's runOnFunction()
7556440fd8SAhmed Charles     // does a std::unique_ptr::reset anyways.
76c26fbbfbSJakob Stoklund Olesen   }
77c26fbbfbSJakob Stoklund Olesen }
78c26fbbfbSJakob Stoklund Olesen 
79587e2741SMatthias Braun template <typename Callable>
foreachUnit(const TargetRegisterInfo * TRI,const LiveInterval & VRegInterval,MCRegister PhysReg,Callable Func)80b7d3311cSBenjamin Kramer static bool foreachUnit(const TargetRegisterInfo *TRI,
81*592f52deSMircea Trofin                         const LiveInterval &VRegInterval, MCRegister PhysReg,
82b7d3311cSBenjamin Kramer                         Callable Func) {
83587e2741SMatthias Braun   if (VRegInterval.hasSubRanges()) {
84587e2741SMatthias Braun     for (MCRegUnitMaskIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
85587e2741SMatthias Braun       unsigned Unit = (*Units).first;
86e6a2485eSMatthias Braun       LaneBitmask Mask = (*Units).second;
87*592f52deSMircea Trofin       for (const LiveInterval::SubRange &S : VRegInterval.subranges()) {
88ea9f8ce0SKrzysztof Parzyszek         if ((S.LaneMask & Mask).any()) {
8909afa1eaSMatthias Braun           if (Func(Unit, S))
90587e2741SMatthias Braun             return true;
91587e2741SMatthias Braun           break;
92587e2741SMatthias Braun         }
93587e2741SMatthias Braun       }
94587e2741SMatthias Braun     }
95587e2741SMatthias Braun   } else {
96587e2741SMatthias Braun     for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
97587e2741SMatthias Braun       if (Func(*Units, VRegInterval))
98587e2741SMatthias Braun         return true;
99587e2741SMatthias Braun     }
100587e2741SMatthias Braun   }
101587e2741SMatthias Braun   return false;
102587e2741SMatthias Braun }
103587e2741SMatthias Braun 
assign(const LiveInterval & VirtReg,MCRegister PhysReg)104*592f52deSMircea Trofin void LiveRegMatrix::assign(const LiveInterval &VirtReg, MCRegister PhysReg) {
1056e85c3d5SMircea Trofin   LLVM_DEBUG(dbgs() << "assigning " << printReg(VirtReg.reg(), TRI) << " to "
106d34e60caSNicola Zaghen                     << printReg(PhysReg, TRI) << ':');
1076e85c3d5SMircea Trofin   assert(!VRM->hasPhys(VirtReg.reg()) && "Duplicate VirtReg assignment");
1086e85c3d5SMircea Trofin   VRM->assignVirt2Phys(VirtReg.reg(), PhysReg);
109587e2741SMatthias Braun 
110d34e60caSNicola Zaghen   foreachUnit(
111d34e60caSNicola Zaghen       TRI, VirtReg, PhysReg, [&](unsigned Unit, const LiveRange &Range) {
112d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << ' ' << Range);
113587e2741SMatthias Braun         Matrix[Unit].unify(VirtReg, Range);
114587e2741SMatthias Braun         return false;
115587e2741SMatthias Braun       });
116587e2741SMatthias Braun 
117c26fbbfbSJakob Stoklund Olesen   ++NumAssigned;
118d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << '\n');
119c26fbbfbSJakob Stoklund Olesen }
120c26fbbfbSJakob Stoklund Olesen 
unassign(const LiveInterval & VirtReg)121*592f52deSMircea Trofin void LiveRegMatrix::unassign(const LiveInterval &VirtReg) {
1226e85c3d5SMircea Trofin   Register PhysReg = VRM->getPhys(VirtReg.reg());
1236e85c3d5SMircea Trofin   LLVM_DEBUG(dbgs() << "unassigning " << printReg(VirtReg.reg(), TRI)
1246e85c3d5SMircea Trofin                     << " from " << printReg(PhysReg, TRI) << ':');
1256e85c3d5SMircea Trofin   VRM->clearVirt(VirtReg.reg());
126587e2741SMatthias Braun 
127d34e60caSNicola Zaghen   foreachUnit(TRI, VirtReg, PhysReg,
128d34e60caSNicola Zaghen               [&](unsigned Unit, const LiveRange &Range) {
129d34e60caSNicola Zaghen                 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI));
130587e2741SMatthias Braun                 Matrix[Unit].extract(VirtReg, Range);
131587e2741SMatthias Braun                 return false;
132587e2741SMatthias Braun               });
133587e2741SMatthias Braun 
134c26fbbfbSJakob Stoklund Olesen   ++NumUnassigned;
135d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << '\n');
136c26fbbfbSJakob Stoklund Olesen }
137c26fbbfbSJakob Stoklund Olesen 
isPhysRegUsed(MCRegister PhysReg) const13843d34799SMircea Trofin bool LiveRegMatrix::isPhysRegUsed(MCRegister PhysReg) const {
139953393a7SMatthias Braun   for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
140953393a7SMatthias Braun     if (!Matrix[*Unit].empty())
141953393a7SMatthias Braun       return true;
142953393a7SMatthias Braun   }
143953393a7SMatthias Braun   return false;
144953393a7SMatthias Braun }
145953393a7SMatthias Braun 
checkRegMaskInterference(const LiveInterval & VirtReg,MCRegister PhysReg)146*592f52deSMircea Trofin bool LiveRegMatrix::checkRegMaskInterference(const LiveInterval &VirtReg,
14743d34799SMircea Trofin                                              MCRegister PhysReg) {
148c26fbbfbSJakob Stoklund Olesen   // Check if the cached information is valid.
149c26fbbfbSJakob Stoklund Olesen   // The same BitVector can be reused for all PhysRegs.
150c26fbbfbSJakob Stoklund Olesen   // We could cache multiple VirtRegs if it becomes necessary.
1516e85c3d5SMircea Trofin   if (RegMaskVirtReg != VirtReg.reg() || RegMaskTag != UserTag) {
1526e85c3d5SMircea Trofin     RegMaskVirtReg = VirtReg.reg();
153c26fbbfbSJakob Stoklund Olesen     RegMaskTag = UserTag;
154c26fbbfbSJakob Stoklund Olesen     RegMaskUsable.clear();
155c26fbbfbSJakob Stoklund Olesen     LIS->checkRegMaskInterference(VirtReg, RegMaskUsable);
156c26fbbfbSJakob Stoklund Olesen   }
157c26fbbfbSJakob Stoklund Olesen 
158c26fbbfbSJakob Stoklund Olesen   // The BitVector is indexed by PhysReg, not register unit.
159c26fbbfbSJakob Stoklund Olesen   // Regmask interference is more fine grained than regunits.
160c26fbbfbSJakob Stoklund Olesen   // For example, a Win64 call can clobber %ymm8 yet preserve %xmm8.
16113dffcb7SJakob Stoklund Olesen   return !RegMaskUsable.empty() && (!PhysReg || !RegMaskUsable.test(PhysReg));
162c26fbbfbSJakob Stoklund Olesen }
163c26fbbfbSJakob Stoklund Olesen 
checkRegUnitInterference(const LiveInterval & VirtReg,MCRegister PhysReg)164*592f52deSMircea Trofin bool LiveRegMatrix::checkRegUnitInterference(const LiveInterval &VirtReg,
16543d34799SMircea Trofin                                              MCRegister PhysReg) {
166c26fbbfbSJakob Stoklund Olesen   if (VirtReg.empty())
167c26fbbfbSJakob Stoklund Olesen     return false;
1686e85c3d5SMircea Trofin   CoalescerPair CP(VirtReg.reg(), PhysReg, *TRI);
169587e2741SMatthias Braun 
170587e2741SMatthias Braun   bool Result = foreachUnit(TRI, VirtReg, PhysReg, [&](unsigned Unit,
171587e2741SMatthias Braun                                                        const LiveRange &Range) {
172587e2741SMatthias Braun     const LiveRange &UnitRange = LIS->getRegUnit(Unit);
173587e2741SMatthias Braun     return Range.overlaps(UnitRange, CP, *LIS->getSlotIndexes());
174587e2741SMatthias Braun   });
175587e2741SMatthias Braun   return Result;
176c26fbbfbSJakob Stoklund Olesen }
177c26fbbfbSJakob Stoklund Olesen 
query(const LiveRange & LR,MCRegister RegUnit)178dbcf9e2eSMatthias Braun LiveIntervalUnion::Query &LiveRegMatrix::query(const LiveRange &LR,
17943d34799SMircea Trofin                                                MCRegister RegUnit) {
180c26fbbfbSJakob Stoklund Olesen   LiveIntervalUnion::Query &Q = Queries[RegUnit];
181dbcf9e2eSMatthias Braun   Q.init(UserTag, LR, Matrix[RegUnit]);
182c26fbbfbSJakob Stoklund Olesen   return Q;
183c26fbbfbSJakob Stoklund Olesen }
184c26fbbfbSJakob Stoklund Olesen 
185c26fbbfbSJakob Stoklund Olesen LiveRegMatrix::InterferenceKind
checkInterference(const LiveInterval & VirtReg,MCRegister PhysReg)186*592f52deSMircea Trofin LiveRegMatrix::checkInterference(const LiveInterval &VirtReg,
187*592f52deSMircea Trofin                                  MCRegister PhysReg) {
188c26fbbfbSJakob Stoklund Olesen   if (VirtReg.empty())
189c26fbbfbSJakob Stoklund Olesen     return IK_Free;
190c26fbbfbSJakob Stoklund Olesen 
191c26fbbfbSJakob Stoklund Olesen   // Regmask interference is the fastest check.
192c26fbbfbSJakob Stoklund Olesen   if (checkRegMaskInterference(VirtReg, PhysReg))
193c26fbbfbSJakob Stoklund Olesen     return IK_RegMask;
194c26fbbfbSJakob Stoklund Olesen 
195c26fbbfbSJakob Stoklund Olesen   // Check for fixed interference.
196c26fbbfbSJakob Stoklund Olesen   if (checkRegUnitInterference(VirtReg, PhysReg))
197c26fbbfbSJakob Stoklund Olesen     return IK_RegUnit;
198c26fbbfbSJakob Stoklund Olesen 
199c26fbbfbSJakob Stoklund Olesen   // Check the matrix for virtual register interference.
200dbcf9e2eSMatthias Braun   bool Interference = foreachUnit(TRI, VirtReg, PhysReg,
20143d34799SMircea Trofin                                   [&](MCRegister Unit, const LiveRange &LR) {
202dbcf9e2eSMatthias Braun                                     return query(LR, Unit).checkInterference();
203dbcf9e2eSMatthias Braun                                   });
204dbcf9e2eSMatthias Braun   if (Interference)
205c26fbbfbSJakob Stoklund Olesen     return IK_VirtReg;
206c26fbbfbSJakob Stoklund Olesen 
207c26fbbfbSJakob Stoklund Olesen   return IK_Free;
208c26fbbfbSJakob Stoklund Olesen }
209cd5bc4a2SMarina Yatsina 
checkInterference(SlotIndex Start,SlotIndex End,MCRegister PhysReg)210cd5bc4a2SMarina Yatsina bool LiveRegMatrix::checkInterference(SlotIndex Start, SlotIndex End,
21143d34799SMircea Trofin                                       MCRegister PhysReg) {
212cd5bc4a2SMarina Yatsina   // Construct artificial live range containing only one segment [Start, End).
213cd5bc4a2SMarina Yatsina   VNInfo valno(0, Start);
214cd5bc4a2SMarina Yatsina   LiveRange::Segment Seg(Start, End, &valno);
215cd5bc4a2SMarina Yatsina   LiveRange LR;
216cd5bc4a2SMarina Yatsina   LR.addSegment(Seg);
217cd5bc4a2SMarina Yatsina 
218cd5bc4a2SMarina Yatsina   // Check for interference with that segment
219cd5bc4a2SMarina Yatsina   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
220ce61def5SMircea Trofin     // LR is stack-allocated. LiveRegMatrix caches queries by a key that
221ce61def5SMircea Trofin     // includes the address of the live range. If (for the same reg unit) this
222ce61def5SMircea Trofin     // checkInterference overload is called twice, without any other query()
223ce61def5SMircea Trofin     // calls in between (on heap-allocated LiveRanges)  - which would invalidate
224ce61def5SMircea Trofin     // the cached query - the LR address seen the second time may well be the
225ce61def5SMircea Trofin     // same as that seen the first time, while the Start/End/valno may not - yet
226ce61def5SMircea Trofin     // the same cached result would be fetched. To avoid that, we don't cache
227ce61def5SMircea Trofin     // this query.
228ce61def5SMircea Trofin     //
229ce61def5SMircea Trofin     // FIXME: the usability of the Query API needs to be improved to avoid
230ce61def5SMircea Trofin     // subtle bugs due to query identity. Avoiding caching, for example, would
231ce61def5SMircea Trofin     // greatly simplify things.
232ce61def5SMircea Trofin     LiveIntervalUnion::Query Q;
233ce61def5SMircea Trofin     Q.reset(UserTag, LR, Matrix[*Units]);
234ce61def5SMircea Trofin     if (Q.checkInterference())
235cd5bc4a2SMarina Yatsina       return true;
236cd5bc4a2SMarina Yatsina   }
237cd5bc4a2SMarina Yatsina   return false;
238cd5bc4a2SMarina Yatsina }
239f80b2987SLuo, Yuanke 
getOneVReg(unsigned PhysReg) const240f80b2987SLuo, Yuanke Register LiveRegMatrix::getOneVReg(unsigned PhysReg) const {
241*592f52deSMircea Trofin   const LiveInterval *VRegInterval = nullptr;
242f80b2987SLuo, Yuanke   for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
243f80b2987SLuo, Yuanke     if ((VRegInterval = Matrix[*Unit].getOneVReg()))
244f80b2987SLuo, Yuanke       return VRegInterval->reg();
245f80b2987SLuo, Yuanke   }
246f80b2987SLuo, Yuanke 
247f80b2987SLuo, Yuanke   return MCRegister::NoRegister;
248f80b2987SLuo, Yuanke }
249