1 //===- LiveRangeCalc.cpp - Calculate live ranges -------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implementation of the LiveRangeCalc class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/LiveRangeCalc.h"
14 #include "llvm/ADT/BitVector.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/CodeGen/LiveInterval.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SlotIndexes.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/MC/LaneBitmask.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
38 #define DEBUG_TYPE "regalloc"
40 // Reserve an address that indicates a value that is known to be "undef".
41 static VNInfo
UndefVNI(0xbad, SlotIndex());
43 void LiveRangeCalc::resetLiveOutMap() {
44 unsigned NumBlocks
= MF
->getNumBlockIDs();
46 Seen
.resize(NumBlocks
);
48 Map
.resize(NumBlocks
);
51 void LiveRangeCalc::reset(const MachineFunction
*mf
,
53 MachineDominatorTree
*MDT
,
54 VNInfo::Allocator
*VNIA
) {
56 MRI
= &MF
->getRegInfo();
64 void LiveRangeCalc::updateFromLiveIns() {
65 LiveRangeUpdater Updater
;
66 for (const LiveInBlock
&I
: LiveIn
) {
69 MachineBasicBlock
*MBB
= I
.DomNode
->getBlock();
70 assert(I
.Value
&& "No live-in value found");
72 std::tie(Start
, End
) = Indexes
->getMBBRange(MBB
);
75 // Value is killed inside this block.
78 // The value is live-through, update LiveOut as well.
79 // Defer the Domtree lookup until it is needed.
80 assert(Seen
.test(MBB
->getNumber()));
81 Map
[MBB
] = LiveOutPair(I
.Value
, nullptr);
83 Updater
.setDest(&I
.LR
);
84 Updater
.add(Start
, End
, I
.Value
);
89 void LiveRangeCalc::extend(LiveRange
&LR
, SlotIndex Use
, unsigned PhysReg
,
90 ArrayRef
<SlotIndex
> Undefs
) {
91 assert(Use
.isValid() && "Invalid SlotIndex");
92 assert(Indexes
&& "Missing SlotIndexes");
93 assert(DomTree
&& "Missing dominator tree");
95 MachineBasicBlock
*UseMBB
= Indexes
->getMBBFromIndex(Use
.getPrevSlot());
96 assert(UseMBB
&& "No MBB at Use");
98 // Is there a def in the same MBB we can extend?
99 auto EP
= LR
.extendInBlock(Undefs
, Indexes
->getMBBStartIdx(UseMBB
), Use
);
100 if (EP
.first
!= nullptr || EP
.second
)
103 // Find the single reaching def, or determine if Use is jointly dominated by
104 // multiple values, and we may need to create even more phi-defs to preserve
105 // VNInfo SSA form. Perform a search for all predecessor blocks where we
106 // know the dominating VNInfo.
107 if (findReachingDefs(LR
, *UseMBB
, Use
, PhysReg
, Undefs
))
110 // When there were multiple different values, we may need new PHIs.
114 // This function is called by a client after using the low-level API to add
115 // live-out and live-in blocks. The unique value optimization is not
116 // available, SplitEditor::transferValues handles that case directly anyway.
117 void LiveRangeCalc::calculateValues() {
118 assert(Indexes
&& "Missing SlotIndexes");
119 assert(DomTree
&& "Missing dominator tree");
124 bool LiveRangeCalc::isDefOnEntry(LiveRange
&LR
, ArrayRef
<SlotIndex
> Undefs
,
125 MachineBasicBlock
&MBB
, BitVector
&DefOnEntry
,
126 BitVector
&UndefOnEntry
) {
127 unsigned BN
= MBB
.getNumber();
130 if (UndefOnEntry
[BN
])
133 auto MarkDefined
= [BN
, &DefOnEntry
](MachineBasicBlock
&B
) -> bool {
134 for (MachineBasicBlock
*S
: B
.successors())
135 DefOnEntry
[S
->getNumber()] = true;
136 DefOnEntry
[BN
] = true;
140 SetVector
<unsigned> WorkList
;
141 // Checking if the entry of MBB is reached by some def: add all predecessors
142 // that are potentially defined-on-exit to the work list.
143 for (MachineBasicBlock
*P
: MBB
.predecessors())
144 WorkList
.insert(P
->getNumber());
146 for (unsigned i
= 0; i
!= WorkList
.size(); ++i
) {
147 // Determine if the exit from the block is reached by some def.
148 unsigned N
= WorkList
[i
];
149 MachineBasicBlock
&B
= *MF
->getBlockNumbered(N
);
151 const LiveOutPair
&LOB
= Map
[&B
];
152 if (LOB
.first
!= nullptr && LOB
.first
!= &UndefVNI
)
153 return MarkDefined(B
);
155 SlotIndex Begin
, End
;
156 std::tie(Begin
, End
) = Indexes
->getMBBRange(&B
);
157 // Treat End as not belonging to B.
158 // If LR has a segment S that starts at the next block, i.e. [End, ...),
159 // std::upper_bound will return the segment following S. Instead,
160 // S should be treated as the first segment that does not overlap B.
161 LiveRange::iterator UB
= upper_bound(LR
, End
.getPrevSlot());
162 if (UB
!= LR
.begin()) {
163 LiveRange::Segment
&Seg
= *std::prev(UB
);
164 if (Seg
.end
> Begin
) {
165 // There is a segment that overlaps B. If the range is not explicitly
166 // undefined between the end of the segment and the end of the block,
167 // treat the block as defined on exit. If it is, go to the next block
169 if (LR
.isUndefIn(Undefs
, Seg
.end
, End
))
171 return MarkDefined(B
);
175 // No segment overlaps with this block. If this block is not defined on
176 // entry, or it undefines the range, do not process its predecessors.
177 if (UndefOnEntry
[N
] || LR
.isUndefIn(Undefs
, Begin
, End
)) {
178 UndefOnEntry
[N
] = true;
182 return MarkDefined(B
);
184 // Still don't know: add all predecessors to the work list.
185 for (MachineBasicBlock
*P
: B
.predecessors())
186 WorkList
.insert(P
->getNumber());
189 UndefOnEntry
[BN
] = true;
193 bool LiveRangeCalc::findReachingDefs(LiveRange
&LR
, MachineBasicBlock
&UseMBB
,
194 SlotIndex Use
, unsigned PhysReg
,
195 ArrayRef
<SlotIndex
> Undefs
) {
196 unsigned UseMBBNum
= UseMBB
.getNumber();
198 // Block numbers where LR should be live-in.
199 SmallVector
<unsigned, 16> WorkList(1, UseMBBNum
);
201 // Remember if we have seen more than one value.
202 bool UniqueVNI
= true;
203 VNInfo
*TheVNI
= nullptr;
205 bool FoundUndef
= false;
207 // Using Seen as a visited set, perform a BFS for all reaching defs.
208 for (unsigned i
= 0; i
!= WorkList
.size(); ++i
) {
209 MachineBasicBlock
*MBB
= MF
->getBlockNumbered(WorkList
[i
]);
212 if (MBB
->pred_empty()) {
213 MBB
->getParent()->verify();
214 errs() << "Use of " << printReg(PhysReg
, MRI
->getTargetRegisterInfo())
215 << " does not have a corresponding definition on every path:\n";
216 const MachineInstr
*MI
= Indexes
->getInstructionFromIndex(Use
);
218 errs() << Use
<< " " << *MI
;
219 report_fatal_error("Use not jointly dominated by defs.");
222 if (Register::isPhysicalRegister(PhysReg
) && !MBB
->isLiveIn(PhysReg
)) {
223 MBB
->getParent()->verify();
224 const TargetRegisterInfo
*TRI
= MRI
->getTargetRegisterInfo();
225 errs() << "The register " << printReg(PhysReg
, TRI
)
226 << " needs to be live in to " << printMBBReference(*MBB
)
227 << ", but is missing from the live-in list.\n";
228 report_fatal_error("Invalid global physical register");
231 FoundUndef
|= MBB
->pred_empty();
233 for (MachineBasicBlock
*Pred
: MBB
->predecessors()) {
234 // Is this a known live-out block?
235 if (Seen
.test(Pred
->getNumber())) {
236 if (VNInfo
*VNI
= Map
[Pred
].first
) {
237 if (TheVNI
&& TheVNI
!= VNI
)
244 SlotIndex Start
, End
;
245 std::tie(Start
, End
) = Indexes
->getMBBRange(Pred
);
247 // First time we see Pred. Try to determine the live-out value, but set
248 // it as null if Pred is live-through with an unknown value.
249 auto EP
= LR
.extendInBlock(Undefs
, Start
, End
);
250 VNInfo
*VNI
= EP
.first
;
251 FoundUndef
|= EP
.second
;
252 setLiveOutValue(Pred
, EP
.second
? &UndefVNI
: VNI
);
254 if (TheVNI
&& TheVNI
!= VNI
)
258 if (VNI
|| EP
.second
)
261 // No, we need a live-in value for Pred as well
263 WorkList
.push_back(Pred
->getNumber());
265 // Loopback to UseMBB, so value is really live through.
271 FoundUndef
|= (TheVNI
== nullptr || TheVNI
== &UndefVNI
);
272 if (!Undefs
.empty() && FoundUndef
)
275 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
276 // neither require it. Skip the sorting overhead for small updates.
277 if (WorkList
.size() > 4)
278 array_pod_sort(WorkList
.begin(), WorkList
.end());
280 // If a unique reaching def was found, blit in the live ranges immediately.
282 assert(TheVNI
!= nullptr && TheVNI
!= &UndefVNI
);
283 LiveRangeUpdater
Updater(&LR
);
284 for (unsigned BN
: WorkList
) {
285 SlotIndex Start
, End
;
286 std::tie(Start
, End
) = Indexes
->getMBBRange(BN
);
287 // Trim the live range in UseMBB.
288 if (BN
== UseMBBNum
&& Use
.isValid())
291 Map
[MF
->getBlockNumbered(BN
)] = LiveOutPair(TheVNI
, nullptr);
292 Updater
.add(Start
, End
, TheVNI
);
297 // Prepare the defined/undefined bit vectors.
298 EntryInfoMap::iterator Entry
;
300 std::tie(Entry
, DidInsert
) = EntryInfos
.insert(
301 std::make_pair(&LR
, std::make_pair(BitVector(), BitVector())));
303 // Initialize newly inserted entries.
304 unsigned N
= MF
->getNumBlockIDs();
305 Entry
->second
.first
.resize(N
);
306 Entry
->second
.second
.resize(N
);
308 BitVector
&DefOnEntry
= Entry
->second
.first
;
309 BitVector
&UndefOnEntry
= Entry
->second
.second
;
311 // Multiple values were found, so transfer the work list to the LiveIn array
312 // where UpdateSSA will use it as a work list.
313 LiveIn
.reserve(WorkList
.size());
314 for (unsigned BN
: WorkList
) {
315 MachineBasicBlock
*MBB
= MF
->getBlockNumbered(BN
);
316 if (!Undefs
.empty() &&
317 !isDefOnEntry(LR
, Undefs
, *MBB
, DefOnEntry
, UndefOnEntry
))
319 addLiveInBlock(LR
, DomTree
->getNode(MBB
));
321 LiveIn
.back().Kill
= Use
;
327 // This is essentially the same iterative algorithm that SSAUpdater uses,
328 // except we already have a dominator tree, so we don't have to recompute it.
329 void LiveRangeCalc::updateSSA() {
330 assert(Indexes
&& "Missing SlotIndexes");
331 assert(DomTree
&& "Missing dominator tree");
333 // Interate until convergence.
337 // Propagate live-out values down the dominator tree, inserting phi-defs
339 for (LiveInBlock
&I
: LiveIn
) {
340 MachineDomTreeNode
*Node
= I
.DomNode
;
341 // Skip block if the live-in value has already been determined.
344 MachineBasicBlock
*MBB
= Node
->getBlock();
345 MachineDomTreeNode
*IDom
= Node
->getIDom();
346 LiveOutPair IDomValue
;
348 // We need a live-in value to a block with no immediate dominator?
349 // This is probably an unreachable block that has survived somehow.
350 bool needPHI
= !IDom
|| !Seen
.test(IDom
->getBlock()->getNumber());
352 // IDom dominates all of our predecessors, but it may not be their
353 // immediate dominator. Check if any of them have live-out values that are
354 // properly dominated by IDom. If so, we need a phi-def here.
356 IDomValue
= Map
[IDom
->getBlock()];
358 // Cache the DomTree node that defined the value.
359 if (IDomValue
.first
&& IDomValue
.first
!= &UndefVNI
&&
361 Map
[IDom
->getBlock()].second
= IDomValue
.second
=
362 DomTree
->getNode(Indexes
->getMBBFromIndex(IDomValue
.first
->def
));
365 for (MachineBasicBlock
*Pred
: MBB
->predecessors()) {
366 LiveOutPair
&Value
= Map
[Pred
];
367 if (!Value
.first
|| Value
.first
== IDomValue
.first
)
369 if (Value
.first
== &UndefVNI
) {
374 // Cache the DomTree node that defined the value.
377 DomTree
->getNode(Indexes
->getMBBFromIndex(Value
.first
->def
));
379 // This predecessor is carrying something other than IDomValue.
380 // It could be because IDomValue hasn't propagated yet, or it could be
381 // because MBB is in the dominance frontier of that value.
382 if (DomTree
->dominates(IDom
, Value
.second
)) {
389 // The value may be live-through even if Kill is set, as can happen when
390 // we are called from extendRange. In that case LiveOutSeen is true, and
391 // LiveOut indicates a foreign or missing value.
392 LiveOutPair
&LOP
= Map
[MBB
];
394 // Create a phi-def if required.
397 assert(Alloc
&& "Need VNInfo allocator to create PHI-defs");
398 SlotIndex Start
, End
;
399 std::tie(Start
, End
) = Indexes
->getMBBRange(MBB
);
400 LiveRange
&LR
= I
.LR
;
401 VNInfo
*VNI
= LR
.getNextValue(Start
, *Alloc
);
403 // This block is done, we know the final value.
406 // Add liveness since updateFromLiveIns now skips this node.
407 if (I
.Kill
.isValid()) {
409 LR
.addSegment(LiveInterval::Segment(Start
, I
.Kill
, VNI
));
412 LR
.addSegment(LiveInterval::Segment(Start
, End
, VNI
));
413 LOP
= LiveOutPair(VNI
, Node
);
415 } else if (IDomValue
.first
&& IDomValue
.first
!= &UndefVNI
) {
416 // No phi-def here. Remember incoming value.
417 I
.Value
= IDomValue
.first
;
419 // If the IDomValue is killed in the block, don't propagate through.
420 if (I
.Kill
.isValid())
423 // Propagate IDomValue if it isn't killed:
424 // MBB is live-out and doesn't define its own value.
425 if (LOP
.first
== IDomValue
.first
)
434 bool LiveRangeCalc::isJointlyDominated(const MachineBasicBlock
*MBB
,
435 ArrayRef
<SlotIndex
> Defs
,
436 const SlotIndexes
&Indexes
) {
437 const MachineFunction
&MF
= *MBB
->getParent();
438 BitVector
DefBlocks(MF
.getNumBlockIDs());
439 for (SlotIndex I
: Defs
)
440 DefBlocks
.set(Indexes
.getMBBFromIndex(I
)->getNumber());
442 SetVector
<unsigned> PredQueue
;
443 PredQueue
.insert(MBB
->getNumber());
444 for (unsigned i
= 0; i
!= PredQueue
.size(); ++i
) {
445 unsigned BN
= PredQueue
[i
];
448 const MachineBasicBlock
*B
= MF
.getBlockNumbered(BN
);
449 for (const MachineBasicBlock
*P
: B
->predecessors())
450 PredQueue
.insert(P
->getNumber());