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