1 //===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the LiveRangeCalc class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LiveRangeCalc.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/CodeGen/MachineDominators.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 
19 using namespace llvm;
20 
21 #define DEBUG_TYPE "regalloc"
22 
23 void LiveRangeCalc::resetLiveOutMap() {
24   unsigned NumBlocks = MF->getNumBlockIDs();
25   Seen.clear();
26   Seen.resize(NumBlocks);
27   EntryInfoMap.clear();
28   Map.resize(NumBlocks);
29 }
30 
31 void LiveRangeCalc::reset(const MachineFunction *mf,
32                           SlotIndexes *SI,
33                           MachineDominatorTree *MDT,
34                           VNInfo::Allocator *VNIA) {
35   MF = mf;
36   MRI = &MF->getRegInfo();
37   Indexes = SI;
38   DomTree = MDT;
39   Alloc = VNIA;
40   resetLiveOutMap();
41   LiveIn.clear();
42 }
43 
44 
45 static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
46                           LiveRange &LR, const MachineOperand &MO) {
47   const MachineInstr &MI = *MO.getParent();
48   SlotIndex DefIdx =
49       Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
50 
51   // Create the def in LR. This may find an existing def.
52   LR.createDeadDef(DefIdx, Alloc);
53 }
54 
55 void LiveRangeCalc::calculate(LiveInterval &LI, bool TrackSubRegs) {
56   assert(MRI && Indexes && "call reset() first");
57 
58   // Step 1: Create minimal live segments for every definition of Reg.
59   // Visit all def operands. If the same instruction has multiple defs of Reg,
60   // createDeadDef() will deduplicate.
61   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
62   unsigned Reg = LI.reg;
63   for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
64     if (!MO.isDef() && !MO.readsReg())
65       continue;
66 
67     unsigned SubReg = MO.getSubReg();
68     if (LI.hasSubRanges() || (SubReg != 0 && TrackSubRegs)) {
69       LaneBitmask WholeMask = MRI->getMaxLaneMaskForVReg(Reg);
70       LaneBitmask SubMask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
71                                         : WholeMask;
72       // If this is the first time we see a subregister def, initialize
73       // subranges by creating a copy of the main range.
74       if (!LI.hasSubRanges() && !LI.empty()) {
75         LaneBitmask ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
76         LI.createSubRangeFrom(*Alloc, ClassMask, LI);
77       }
78 
79       LaneBitmask Mask = SubMask;
80       for (LiveInterval::SubRange &S : LI.subranges()) {
81         // A Mask for subregs common to the existing subrange and current def.
82         LaneBitmask Common = S.LaneMask & Mask;
83         if (Common == 0)
84           continue;
85         LiveInterval::SubRange *CommonRange;
86         // A Mask for subregs covered by the subrange but not the current def.
87         if (LaneBitmask RM = S.LaneMask & ~Mask) {
88           // Split the subrange S into two parts: one covered by the current
89           // def (CommonRange), and the one not affected by it (updated S).
90           S.LaneMask = RM;
91           CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
92         } else {
93           assert(Common == S.LaneMask);
94           CommonRange = &S;
95         }
96         if (MO.isDef())
97           createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
98         Mask &= ~Common;
99       }
100       // Create a new SubRange for subregs we did not cover yet.
101       if (Mask != 0) {
102         LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
103         if (MO.isDef())
104           createDeadDef(*Indexes, *Alloc, *NewRange, MO);
105       }
106     }
107 
108     // Create the def in the main liverange. We do not have to do this if
109     // subranges are tracked as we recreate the main range later in this case.
110     if (MO.isDef() && !LI.hasSubRanges())
111       createDeadDef(*Indexes, *Alloc, LI, MO);
112   }
113 
114   // We may have created empty live ranges for partially undefined uses, we
115   // can't keep them because we won't find defs in them later.
116   LI.removeEmptySubRanges();
117 
118   // Step 2: Extend live segments to all uses, constructing SSA form as
119   // necessary.
120   if (LI.hasSubRanges()) {
121     for (LiveInterval::SubRange &S : LI.subranges()) {
122       LiveRangeCalc SubLRC;
123       SubLRC.reset(MF, Indexes, DomTree, Alloc);
124       SubLRC.extendToUses(S, Reg, S.LaneMask, &LI);
125     }
126     LI.clear();
127     constructMainRangeFromSubranges(LI);
128   } else {
129     resetLiveOutMap();
130     extendToUses(LI, Reg, ~0u);
131   }
132 }
133 
134 void LiveRangeCalc::constructMainRangeFromSubranges(LiveInterval &LI) {
135   // First create dead defs at all defs found in subranges.
136   LiveRange &MainRange = LI;
137   assert(MainRange.segments.empty() && MainRange.valnos.empty() &&
138          "Expect empty main liverange");
139 
140   for (const LiveInterval::SubRange &SR : LI.subranges()) {
141     for (const VNInfo *VNI : SR.valnos) {
142       if (!VNI->isUnused() && !VNI->isPHIDef())
143         MainRange.createDeadDef(VNI->def, *Alloc);
144     }
145   }
146   resetLiveOutMap();
147   extendToUses(MainRange, LI.reg, ~0U, &LI);
148 }
149 
150 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
151   assert(MRI && Indexes && "call reset() first");
152 
153   // Visit all def operands. If the same instruction has multiple defs of Reg,
154   // LR.createDeadDef() will deduplicate.
155   for (MachineOperand &MO : MRI->def_operands(Reg))
156     createDeadDef(*Indexes, *Alloc, LR, MO);
157 }
158 
159 
160 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, LaneBitmask Mask,
161                                  LiveInterval *LI) {
162   SmallVector<SlotIndex, 4> Undefs;
163   if (LI != nullptr)
164     LI->computeSubRangeUndefs(Undefs, Mask, *MRI, *Indexes);
165 
166   // Visit all operands that read Reg. This may include partial defs.
167   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
168   for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
169     // Clear all kill flags. They will be reinserted after register allocation
170     // by LiveIntervalAnalysis::addKillFlags().
171     if (MO.isUse())
172       MO.setIsKill(false);
173     if (!MO.readsReg())
174       continue;
175 
176     unsigned SubReg = MO.getSubReg();
177     if (SubReg != 0) {
178       LaneBitmask SLM = TRI.getSubRegIndexLaneMask(SubReg);
179       if (MO.isDef())
180         SLM = MRI->getMaxLaneMaskForVReg(Reg) & ~SLM;
181       // Ignore uses not covering the current subrange.
182       if ((SLM & Mask) == 0)
183         continue;
184     }
185 
186     // Determine the actual place of the use.
187     const MachineInstr *MI = MO.getParent();
188     unsigned OpNo = (&MO - &MI->getOperand(0));
189     SlotIndex UseIdx;
190     if (MI->isPHI()) {
191       assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
192       // The actual place where a phi operand is used is the end of the pred
193       // MBB. PHI operands are paired: (Reg, PredMBB).
194       UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
195     } else {
196       // Check for early-clobber redefs.
197       bool isEarlyClobber = false;
198       unsigned DefIdx;
199       if (MO.isDef())
200         isEarlyClobber = MO.isEarlyClobber();
201       else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
202         // FIXME: This would be a lot easier if tied early-clobber uses also
203         // had an early-clobber flag.
204         isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
205       }
206       UseIdx = Indexes->getInstructionIndex(*MI).getRegSlot(isEarlyClobber);
207     }
208 
209     // MI is reading Reg. We may have visited MI before if it happens to be
210     // reading Reg multiple times. That is OK, extend() is idempotent.
211     extend(LR, UseIdx, Reg, Undefs);
212   }
213 }
214 
215 
216 void LiveRangeCalc::updateFromLiveIns() {
217   LiveRangeUpdater Updater;
218   for (const LiveInBlock &I : LiveIn) {
219     if (!I.DomNode)
220       continue;
221     MachineBasicBlock *MBB = I.DomNode->getBlock();
222     assert(I.Value && "No live-in value found");
223     SlotIndex Start, End;
224     std::tie(Start, End) = Indexes->getMBBRange(MBB);
225 
226     if (I.Kill.isValid())
227       // Value is killed inside this block.
228       End = I.Kill;
229     else {
230       // The value is live-through, update LiveOut as well.
231       // Defer the Domtree lookup until it is needed.
232       assert(Seen.test(MBB->getNumber()));
233       Map[MBB] = LiveOutPair(I.Value, nullptr);
234     }
235     Updater.setDest(&I.LR);
236     Updater.add(Start, End, I.Value);
237   }
238   LiveIn.clear();
239 }
240 
241 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg,
242                            ArrayRef<SlotIndex> Undefs) {
243   assert(Use.isValid() && "Invalid SlotIndex");
244   assert(Indexes && "Missing SlotIndexes");
245   assert(DomTree && "Missing dominator tree");
246 
247   MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
248   assert(UseMBB && "No MBB at Use");
249 
250   // Is there a def in the same MBB we can extend?
251   auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
252   if (EP.first != nullptr || EP.second)
253     return;
254 
255   // Find the single reaching def, or determine if Use is jointly dominated by
256   // multiple values, and we may need to create even more phi-defs to preserve
257   // VNInfo SSA form.  Perform a search for all predecessor blocks where we
258   // know the dominating VNInfo.
259   if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
260     return;
261 
262   // When there were multiple different values, we may need new PHIs.
263   calculateValues();
264 }
265 
266 
267 // This function is called by a client after using the low-level API to add
268 // live-out and live-in blocks.  The unique value optimization is not
269 // available, SplitEditor::transferValues handles that case directly anyway.
270 void LiveRangeCalc::calculateValues() {
271   assert(Indexes && "Missing SlotIndexes");
272   assert(DomTree && "Missing dominator tree");
273   updateSSA();
274   updateFromLiveIns();
275 }
276 
277 
278 bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
279                                  MachineBasicBlock &MBB, BitVector &DefOnEntry,
280                                  BitVector &UndefOnEntry) {
281   unsigned BN = MBB.getNumber();
282   if (DefOnEntry[BN])
283     return true;
284   if (UndefOnEntry[BN])
285     return false;
286 
287   auto MarkDefined =
288         [this,BN,&DefOnEntry,&UndefOnEntry] (MachineBasicBlock &B) -> bool {
289     for (MachineBasicBlock *S : B.successors())
290       DefOnEntry[S->getNumber()] = true;
291     DefOnEntry[BN] = true;
292     return true;
293   };
294 
295   SetVector<unsigned> WorkList;
296   // Checking if the entry of MBB is reached by some def: add all predecessors
297   // that are potentially defined-on-exit to the work list.
298   for (MachineBasicBlock *P : MBB.predecessors())
299     WorkList.insert(P->getNumber());
300 
301   for (unsigned i = 0; i != WorkList.size(); ++i) {
302     // Determine if the exit from the block is reached by some def.
303     unsigned N = WorkList[i];
304     MachineBasicBlock &B = *MF->getBlockNumbered(N);
305     if (Seen[N] && Map[&B].first != nullptr)
306       return MarkDefined(B);
307     SlotIndex Begin, End;
308     std::tie(Begin, End) = Indexes->getMBBRange(&B);
309     LiveRange::iterator UB = std::upper_bound(LR.begin(), LR.end(), End);
310     if (UB != LR.begin()) {
311       LiveRange::Segment &Seg = *std::prev(UB);
312       if (Seg.end > Begin) {
313         // There is a segment that overlaps B. If the range is not explicitly
314         // undefined between the end of the segment and the end of the block,
315         // treat the block as defined on exit. If it is, go to the next block
316         // on the work list.
317         if (LR.isUndefIn(Undefs, Seg.end, End))
318           continue;
319         return MarkDefined(B);
320       }
321     }
322 
323     // No segment overlaps with this block. If this block is not defined on
324     // entry, or it undefines the range, do not process its predecessors.
325     if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
326       UndefOnEntry[N] = true;
327       continue;
328     }
329     if (DefOnEntry[N])
330       return MarkDefined(B);
331 
332     // Still don't know: add all predecessors to the work list.
333     for (MachineBasicBlock *P : B.predecessors())
334       WorkList.insert(P->getNumber());
335   }
336 
337   UndefOnEntry[BN] = true;
338   return false;
339 }
340 
341 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
342                                      SlotIndex Use, unsigned PhysReg,
343                                      ArrayRef<SlotIndex> Undefs) {
344   unsigned UseMBBNum = UseMBB.getNumber();
345 
346   // Block numbers where LR should be live-in.
347   SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
348 
349   // Remember if we have seen more than one value.
350   bool UniqueVNI = true;
351   VNInfo *TheVNI = nullptr;
352 
353   bool FoundUndef = false;
354 
355   // Using Seen as a visited set, perform a BFS for all reaching defs.
356   for (unsigned i = 0; i != WorkList.size(); ++i) {
357     MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
358 
359 #ifndef NDEBUG
360     if (Undefs.size() > 0 && MBB->pred_empty()) {
361       MBB->getParent()->verify();
362       errs() << "Use of " << PrintReg(PhysReg)
363              << " does not have a corresponding definition on every path:\n";
364       const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
365       if (MI != nullptr)
366         errs() << Use << " " << *MI;
367       llvm_unreachable("Use not jointly dominated by defs.");
368     }
369 
370     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
371         !MBB->isLiveIn(PhysReg)) {
372       MBB->getParent()->verify();
373       errs() << "The register " << PrintReg(PhysReg)
374              << " needs to be live in to BB#" << MBB->getNumber()
375              << ", but is missing from the live-in list.\n";
376       llvm_unreachable("Invalid global physical register");
377     }
378 #endif
379     FoundUndef |= MBB->pred_empty();
380 
381     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
382          PE = MBB->pred_end(); PI != PE; ++PI) {
383        MachineBasicBlock *Pred = *PI;
384 
385        // Is this a known live-out block?
386        if (Seen.test(Pred->getNumber())) {
387          if (VNInfo *VNI = Map[Pred].first) {
388            if (TheVNI && TheVNI != VNI)
389              UniqueVNI = false;
390            TheVNI = VNI;
391          }
392          continue;
393        }
394 
395        SlotIndex Start, End;
396        std::tie(Start, End) = Indexes->getMBBRange(Pred);
397 
398        // First time we see Pred.  Try to determine the live-out value, but set
399        // it as null if Pred is live-through with an unknown value.
400        auto EP = LR.extendInBlock(Undefs, Start, End);
401        VNInfo *VNI = EP.first;
402        FoundUndef |= EP.second;
403        setLiveOutValue(Pred, VNI);
404        if (VNI) {
405          if (TheVNI && TheVNI != VNI)
406            UniqueVNI = false;
407          TheVNI = VNI;
408        }
409        if (VNI || EP.second)
410          continue;
411 
412        // No, we need a live-in value for Pred as well
413        if (Pred != &UseMBB)
414          WorkList.push_back(Pred->getNumber());
415        else
416           // Loopback to UseMBB, so value is really live through.
417          Use = SlotIndex();
418     }
419   }
420 
421   LiveIn.clear();
422   FoundUndef |= (TheVNI == nullptr);
423   if (Undefs.size() > 0 && FoundUndef)
424     UniqueVNI = false;
425 
426   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
427   // neither require it. Skip the sorting overhead for small updates.
428   if (WorkList.size() > 4)
429     array_pod_sort(WorkList.begin(), WorkList.end());
430 
431   // If a unique reaching def was found, blit in the live ranges immediately.
432   if (UniqueVNI) {
433     assert(TheVNI != nullptr);
434     LiveRangeUpdater Updater(&LR);
435     for (unsigned BN : WorkList) {
436       SlotIndex Start, End;
437       std::tie(Start, End) = Indexes->getMBBRange(BN);
438       // Trim the live range in UseMBB.
439       if (BN == UseMBBNum && Use.isValid())
440         End = Use;
441       else
442         Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
443       Updater.add(Start, End, TheVNI);
444     }
445     return true;
446   }
447 
448   // Prepare the defined/undefined bit vectors.
449   auto EF = EntryInfoMap.find(&LR);
450   if (EF == EntryInfoMap.end()) {
451     unsigned N = MF->getNumBlockIDs();
452     EF = EntryInfoMap.insert({&LR, {BitVector(), BitVector()}}).first;
453     EF->second.first.resize(N);
454     EF->second.second.resize(N);
455   }
456   BitVector &DefOnEntry = EF->second.first;
457   BitVector &UndefOnEntry = EF->second.second;
458 
459   // Multiple values were found, so transfer the work list to the LiveIn array
460   // where UpdateSSA will use it as a work list.
461   LiveIn.reserve(WorkList.size());
462   for (unsigned BN : WorkList) {
463     MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
464     if (Undefs.size() > 0 && !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
465       continue;
466     addLiveInBlock(LR, DomTree->getNode(MBB));
467     if (MBB == &UseMBB)
468       LiveIn.back().Kill = Use;
469   }
470 
471   return false;
472 }
473 
474 
475 // This is essentially the same iterative algorithm that SSAUpdater uses,
476 // except we already have a dominator tree, so we don't have to recompute it.
477 void LiveRangeCalc::updateSSA() {
478   assert(Indexes && "Missing SlotIndexes");
479   assert(DomTree && "Missing dominator tree");
480 
481   // Interate until convergence.
482   unsigned Changes;
483   do {
484     Changes = 0;
485     // Propagate live-out values down the dominator tree, inserting phi-defs
486     // when necessary.
487     for (LiveInBlock &I : LiveIn) {
488       MachineDomTreeNode *Node = I.DomNode;
489       // Skip block if the live-in value has already been determined.
490       if (!Node)
491         continue;
492       MachineBasicBlock *MBB = Node->getBlock();
493       MachineDomTreeNode *IDom = Node->getIDom();
494       LiveOutPair IDomValue;
495 
496       // We need a live-in value to a block with no immediate dominator?
497       // This is probably an unreachable block that has survived somehow.
498       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
499 
500       // IDom dominates all of our predecessors, but it may not be their
501       // immediate dominator. Check if any of them have live-out values that are
502       // properly dominated by IDom. If so, we need a phi-def here.
503       if (!needPHI) {
504         IDomValue = Map[IDom->getBlock()];
505 
506         // Cache the DomTree node that defined the value.
507         if (IDomValue.first && !IDomValue.second)
508           Map[IDom->getBlock()].second = IDomValue.second =
509             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
510 
511         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
512                PE = MBB->pred_end(); PI != PE; ++PI) {
513           LiveOutPair &Value = Map[*PI];
514           if (!Value.first || Value.first == IDomValue.first)
515             continue;
516 
517           // Cache the DomTree node that defined the value.
518           if (!Value.second)
519             Value.second =
520               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
521 
522           // This predecessor is carrying something other than IDomValue.
523           // It could be because IDomValue hasn't propagated yet, or it could be
524           // because MBB is in the dominance frontier of that value.
525           if (DomTree->dominates(IDom, Value.second)) {
526             needPHI = true;
527             break;
528           }
529         }
530       }
531 
532       // The value may be live-through even if Kill is set, as can happen when
533       // we are called from extendRange. In that case LiveOutSeen is true, and
534       // LiveOut indicates a foreign or missing value.
535       LiveOutPair &LOP = Map[MBB];
536 
537       // Create a phi-def if required.
538       if (needPHI) {
539         ++Changes;
540         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
541         SlotIndex Start, End;
542         std::tie(Start, End) = Indexes->getMBBRange(MBB);
543         LiveRange &LR = I.LR;
544         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
545         I.Value = VNI;
546         // This block is done, we know the final value.
547         I.DomNode = nullptr;
548 
549         // Add liveness since updateFromLiveIns now skips this node.
550         if (I.Kill.isValid()) {
551           if (VNI)
552             LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
553         } else {
554           if (VNI)
555             LR.addSegment(LiveInterval::Segment(Start, End, VNI));
556           LOP = LiveOutPair(VNI, Node);
557         }
558       } else if (IDomValue.first) {
559         // No phi-def here. Remember incoming value.
560         I.Value = IDomValue.first;
561 
562         // If the IDomValue is killed in the block, don't propagate through.
563         if (I.Kill.isValid())
564           continue;
565 
566         // Propagate IDomValue if it isn't killed:
567         // MBB is live-out and doesn't define its own value.
568         if (LOP.first == IDomValue.first)
569           continue;
570         ++Changes;
571         LOP = IDomValue;
572       }
573     }
574   } while (Changes);
575 }
576