1 //===- LiveRangeCalc.cpp - Calculate live ranges -------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implementation of the LiveRangeCalc class.
10 //
11 //===----------------------------------------------------------------------===//
12 
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"
30 #include <algorithm>
31 #include <cassert>
32 #include <iterator>
33 #include <tuple>
34 #include <utility>
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "regalloc"
39 
40 // Reserve an address that indicates a value that is known to be "undef".
41 static VNInfo UndefVNI(0xbad, SlotIndex());
42 
resetLiveOutMap()43 void LiveRangeCalc::resetLiveOutMap() {
44   unsigned NumBlocks = MF->getNumBlockIDs();
45   Seen.clear();
46   Seen.resize(NumBlocks);
47   EntryInfos.clear();
48   Map.resize(NumBlocks);
49 }
50 
reset(const MachineFunction * mf,SlotIndexes * SI,MachineDominatorTree * MDT,VNInfo::Allocator * VNIA)51 void LiveRangeCalc::reset(const MachineFunction *mf,
52                           SlotIndexes *SI,
53                           MachineDominatorTree *MDT,
54                           VNInfo::Allocator *VNIA) {
55   MF = mf;
56   MRI = &MF->getRegInfo();
57   Indexes = SI;
58   DomTree = MDT;
59   Alloc = VNIA;
60   resetLiveOutMap();
61   LiveIn.clear();
62 }
63 
updateFromLiveIns()64 void LiveRangeCalc::updateFromLiveIns() {
65   LiveRangeUpdater Updater;
66   for (const LiveInBlock &I : LiveIn) {
67     if (!I.DomNode)
68       continue;
69     MachineBasicBlock *MBB = I.DomNode->getBlock();
70     assert(I.Value && "No live-in value found");
71     SlotIndex Start, End;
72     std::tie(Start, End) = Indexes->getMBBRange(MBB);
73 
74     if (I.Kill.isValid())
75       // Value is killed inside this block.
76       End = I.Kill;
77     else {
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);
82     }
83     Updater.setDest(&I.LR);
84     Updater.add(Start, End, I.Value);
85   }
86   LiveIn.clear();
87 }
88 
extend(LiveRange & LR,SlotIndex Use,unsigned PhysReg,ArrayRef<SlotIndex> Undefs)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");
94 
95   MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
96   assert(UseMBB && "No MBB at Use");
97 
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)
101     return;
102 
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))
108     return;
109 
110   // When there were multiple different values, we may need new PHIs.
111   calculateValues();
112 }
113 
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.
calculateValues()117 void LiveRangeCalc::calculateValues() {
118   assert(Indexes && "Missing SlotIndexes");
119   assert(DomTree && "Missing dominator tree");
120   updateSSA();
121   updateFromLiveIns();
122 }
123 
isDefOnEntry(LiveRange & LR,ArrayRef<SlotIndex> Undefs,MachineBasicBlock & MBB,BitVector & DefOnEntry,BitVector & UndefOnEntry)124 bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
125                                  MachineBasicBlock &MBB, BitVector &DefOnEntry,
126                                  BitVector &UndefOnEntry) {
127   unsigned BN = MBB.getNumber();
128   if (DefOnEntry[BN])
129     return true;
130   if (UndefOnEntry[BN])
131     return false;
132 
133   auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
134     for (MachineBasicBlock *S : B.successors())
135       DefOnEntry[S->getNumber()] = true;
136     DefOnEntry[BN] = true;
137     return true;
138   };
139 
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());
145 
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);
150     if (Seen[N]) {
151       const LiveOutPair &LOB = Map[&B];
152       if (LOB.first != nullptr && LOB.first != &UndefVNI)
153         return MarkDefined(B);
154     }
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
168         // on the work list.
169         if (LR.isUndefIn(Undefs, Seg.end, End))
170           continue;
171         return MarkDefined(B);
172       }
173     }
174 
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;
179       continue;
180     }
181     if (DefOnEntry[N])
182       return MarkDefined(B);
183 
184     // Still don't know: add all predecessors to the work list.
185     for (MachineBasicBlock *P : B.predecessors())
186       WorkList.insert(P->getNumber());
187   }
188 
189   UndefOnEntry[BN] = true;
190   return false;
191 }
192 
findReachingDefs(LiveRange & LR,MachineBasicBlock & UseMBB,SlotIndex Use,unsigned PhysReg,ArrayRef<SlotIndex> Undefs)193 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
194                                      SlotIndex Use, unsigned PhysReg,
195                                      ArrayRef<SlotIndex> Undefs) {
196   unsigned UseMBBNum = UseMBB.getNumber();
197 
198   // Block numbers where LR should be live-in.
199   SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
200 
201   // Remember if we have seen more than one value.
202   bool UniqueVNI = true;
203   VNInfo *TheVNI = nullptr;
204 
205   bool FoundUndef = false;
206 
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]);
210 
211 #ifndef NDEBUG
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);
217       if (MI != nullptr)
218         errs() << Use << " " << *MI;
219       report_fatal_error("Use not jointly dominated by defs.");
220     }
221 
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");
229     }
230 #endif
231     FoundUndef |= MBB->pred_empty();
232 
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)
238              UniqueVNI = false;
239            TheVNI = VNI;
240          }
241          continue;
242        }
243 
244        SlotIndex Start, End;
245        std::tie(Start, End) = Indexes->getMBBRange(Pred);
246 
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);
253        if (VNI) {
254          if (TheVNI && TheVNI != VNI)
255            UniqueVNI = false;
256          TheVNI = VNI;
257        }
258        if (VNI || EP.second)
259          continue;
260 
261        // No, we need a live-in value for Pred as well
262        if (Pred != &UseMBB)
263          WorkList.push_back(Pred->getNumber());
264        else
265           // Loopback to UseMBB, so value is really live through.
266          Use = SlotIndex();
267     }
268   }
269 
270   LiveIn.clear();
271   FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
272   if (!Undefs.empty() && FoundUndef)
273     UniqueVNI = false;
274 
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());
279 
280   // If a unique reaching def was found, blit in the live ranges immediately.
281   if (UniqueVNI) {
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())
289         End = Use;
290       else
291         Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
292       Updater.add(Start, End, TheVNI);
293     }
294     return true;
295   }
296 
297   // Prepare the defined/undefined bit vectors.
298   EntryInfoMap::iterator Entry;
299   bool DidInsert;
300   std::tie(Entry, DidInsert) = EntryInfos.insert(
301       std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
302   if (DidInsert) {
303     // Initialize newly inserted entries.
304     unsigned N = MF->getNumBlockIDs();
305     Entry->second.first.resize(N);
306     Entry->second.second.resize(N);
307   }
308   BitVector &DefOnEntry = Entry->second.first;
309   BitVector &UndefOnEntry = Entry->second.second;
310 
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))
318       continue;
319     addLiveInBlock(LR, DomTree->getNode(MBB));
320     if (MBB == &UseMBB)
321       LiveIn.back().Kill = Use;
322   }
323 
324   return false;
325 }
326 
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.
updateSSA()329 void LiveRangeCalc::updateSSA() {
330   assert(Indexes && "Missing SlotIndexes");
331   assert(DomTree && "Missing dominator tree");
332 
333   // Interate until convergence.
334   bool Changed;
335   do {
336     Changed = false;
337     // Propagate live-out values down the dominator tree, inserting phi-defs
338     // when necessary.
339     for (LiveInBlock &I : LiveIn) {
340       MachineDomTreeNode *Node = I.DomNode;
341       // Skip block if the live-in value has already been determined.
342       if (!Node)
343         continue;
344       MachineBasicBlock *MBB = Node->getBlock();
345       MachineDomTreeNode *IDom = Node->getIDom();
346       LiveOutPair IDomValue;
347 
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());
351 
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.
355       if (!needPHI) {
356         IDomValue = Map[IDom->getBlock()];
357 
358         // Cache the DomTree node that defined the value.
359         if (IDomValue.first && IDomValue.first != &UndefVNI &&
360             !IDomValue.second) {
361           Map[IDom->getBlock()].second = IDomValue.second =
362             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
363         }
364 
365         for (MachineBasicBlock *Pred : MBB->predecessors()) {
366           LiveOutPair &Value = Map[Pred];
367           if (!Value.first || Value.first == IDomValue.first)
368             continue;
369           if (Value.first == &UndefVNI) {
370             needPHI = true;
371             break;
372           }
373 
374           // Cache the DomTree node that defined the value.
375           if (!Value.second)
376             Value.second =
377               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
378 
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)) {
383             needPHI = true;
384             break;
385           }
386         }
387       }
388 
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];
393 
394       // Create a phi-def if required.
395       if (needPHI) {
396         Changed = true;
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);
402         I.Value = VNI;
403         // This block is done, we know the final value.
404         I.DomNode = nullptr;
405 
406         // Add liveness since updateFromLiveIns now skips this node.
407         if (I.Kill.isValid()) {
408           if (VNI)
409             LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
410         } else {
411           if (VNI)
412             LR.addSegment(LiveInterval::Segment(Start, End, VNI));
413           LOP = LiveOutPair(VNI, Node);
414         }
415       } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
416         // No phi-def here. Remember incoming value.
417         I.Value = IDomValue.first;
418 
419         // If the IDomValue is killed in the block, don't propagate through.
420         if (I.Kill.isValid())
421           continue;
422 
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)
426           continue;
427         Changed = true;
428         LOP = IDomValue;
429       }
430     }
431   } while (Changed);
432 }
433 
isJointlyDominated(const MachineBasicBlock * MBB,ArrayRef<SlotIndex> Defs,const SlotIndexes & Indexes)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());
441 
442   SetVector<unsigned> PredQueue;
443   PredQueue.insert(MBB->getNumber());
444   for (unsigned i = 0; i != PredQueue.size(); ++i) {
445     unsigned BN = PredQueue[i];
446     if (DefBlocks[BN])
447       return true;
448     const MachineBasicBlock *B = MF.getBlockNumbered(BN);
449     for (const MachineBasicBlock *P : B->predecessors())
450       PredQueue.insert(P->getNumber());
451   }
452   return false;
453 }
454