LiveRangeCalc: Rewrite subrange calculation
[oota-llvm.git] / lib / CodeGen / LiveRangeCalc.cpp
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/CodeGen/MachineDominators.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17
18 using namespace llvm;
19
20 #define DEBUG_TYPE "regalloc"
21
22 void LiveRangeCalc::reset(const MachineFunction *mf,
23                           SlotIndexes *SI,
24                           MachineDominatorTree *MDT,
25                           VNInfo::Allocator *VNIA) {
26   MF = mf;
27   MRI = &MF->getRegInfo();
28   Indexes = SI;
29   DomTree = MDT;
30   Alloc = VNIA;
31
32   unsigned NumBlocks = MF->getNumBlockIDs();
33   Seen.clear();
34   Seen.resize(NumBlocks);
35   Map.resize(NumBlocks);
36 }
37
38
39 static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc,
40                           LiveRange &LR, const MachineOperand &MO) {
41     const MachineInstr *MI = MO.getParent();
42     SlotIndex DefIdx;
43     if (MI->isPHI()) {
44       DefIdx = Indexes.getMBBStartIdx(MI->getParent());
45     } else {
46       DefIdx = Indexes.getInstructionIndex(MI).getRegSlot(MO.isEarlyClobber());
47     }
48     // Create the def in LR. This may find an existing def.
49     LR.createDeadDef(DefIdx, Alloc);
50 }
51
52 void LiveRangeCalc::calculate(LiveInterval &LI) {
53   assert(MRI && Indexes && "call reset() first");
54
55   // Step 1: Create minimal live segments for every definition of Reg.
56   // Visit all def operands. If the same instruction has multiple defs of Reg,
57   // LR.createDeadDef() will deduplicate.
58   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
59   unsigned Reg = LI.reg;
60   for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
61     unsigned SubReg = MO.getSubReg();
62     if (LI.hasSubRanges() || (SubReg != 0 && MRI->tracksSubRegLiveness())) {
63       unsigned Mask = SubReg != 0 ? TRI.getSubRegIndexLaneMask(SubReg)
64                                   : MRI->getMaxLaneMaskForVReg(Reg);
65
66       // If this is the first time we see a subregister def, initialize
67       // subranges by creating a copy of the main range.
68       if (!LI.hasSubRanges() && !LI.empty()) {
69         unsigned ClassMask = MRI->getMaxLaneMaskForVReg(Reg);
70         LI.createSubRangeFrom(*Alloc, ClassMask, LI);
71       }
72
73       for (LiveInterval::SubRange &S : LI.subranges()) {
74         // A Mask for subregs common to the existing subrange and current def.
75         unsigned Common = S.LaneMask & Mask;
76         if (Common == 0)
77           continue;
78         // A Mask for subregs covered by the subrange but not the current def.
79         unsigned LRest = S.LaneMask & ~Mask;
80         LiveInterval::SubRange *CommonRange;
81         if (LRest != 0) {
82           // Split current subrange into Common and LRest ranges.
83           S.LaneMask = LRest;
84           CommonRange = LI.createSubRangeFrom(*Alloc, Common, S);
85         } else {
86           assert(Common == S.LaneMask);
87           CommonRange = &S;
88         }
89         if (MO.isDef())
90           createDeadDef(*Indexes, *Alloc, *CommonRange, MO);
91         Mask &= ~Common;
92       }
93       // Create a new SubRange for subregs we did not cover yet.
94       if (Mask != 0) {
95         LiveInterval::SubRange *NewRange = LI.createSubRange(*Alloc, Mask);
96         if (MO.isDef())
97           createDeadDef(*Indexes, *Alloc, *NewRange, MO);
98       }
99     }
100
101     // Create the def in the main liverange.
102     if (MO.isDef())
103       createDeadDef(*Indexes, *Alloc, LI, MO);
104   }
105
106   // Step 2: Extend live segments to all uses, constructing SSA form as
107   // necessary.
108   for (LiveInterval::SubRange &S : LI.subranges()) {
109     extendToUses(S, Reg, S.LaneMask);
110   }
111   extendToUses(LI, Reg, ~0u);
112 }
113
114
115 void LiveRangeCalc::calculate(LiveRange &LR, unsigned Reg, bool IgnoreUses) {
116   assert(MRI && Indexes && "call reset() first");
117
118   // Step 1: Create minimal live segments for every definition of Reg.
119   // Visit all def operands. If the same instruction has multiple defs of Reg,
120   // LR.createDeadDef() will deduplicate.
121   for (MachineOperand &MO : MRI->def_operands(Reg)) {
122     createDeadDef(*Indexes, *Alloc, LR, MO);
123   }
124
125   // Step 2: Extend live segments to all uses, constructing SSA form as
126   // necessary.
127   if (!IgnoreUses)
128     extendToUses(LR, Reg, ~0u);
129 }
130
131
132 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg, unsigned Mask) {
133   unsigned NumBlocks = MF->getNumBlockIDs();
134   Seen.clear();
135   Seen.resize(NumBlocks);
136   Map.resize(NumBlocks);
137
138   // Visit all operands that read Reg. This may include partial defs.
139   const TargetRegisterInfo &TRI = *MRI->getTargetRegisterInfo();
140   for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
141     // Clear all kill flags. They will be reinserted after register allocation
142     // by LiveIntervalAnalysis::addKillFlags().
143     if (MO.isUse())
144       MO.setIsKill(false);
145     // We are only interested in uses. For the main range this also includes
146     // the reads happening on partial register defs.
147     if (!MO.isUse() && (!MO.readsReg() || Mask != ~0u))
148       continue;
149     unsigned SubReg = MO.getSubReg();
150     if (SubReg != 0) {
151       unsigned SubRegMask = TRI.getSubRegIndexLaneMask(SubReg);
152       // Ignore uses not covering the current subrange.
153       if ((SubRegMask & Mask) == 0)
154         continue;
155       // The create dead-defs logic in calculate() splits subranges as fine as
156       // necessary for all uses, so SubRegMask shouldn't be smaller than Mask.
157       assert((SubRegMask & ~Mask) == 0);
158     }
159
160     // Determine the actual place of the use.
161     const MachineInstr *MI = MO.getParent();
162     unsigned OpNo = (&MO - &MI->getOperand(0));
163     SlotIndex UseIdx;
164     if (MI->isPHI()) {
165       assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
166       // The actual place where a phi operand is used is the end of the pred
167       // MBB. PHI operands are paired: (Reg, PredMBB).
168       UseIdx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
169     } else {
170       // Check for early-clobber redefs.
171       bool isEarlyClobber = false;
172       unsigned DefIdx;
173       if (MO.isDef()) {
174         isEarlyClobber = MO.isEarlyClobber();
175       } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
176         // FIXME: This would be a lot easier if tied early-clobber uses also
177         // had an early-clobber flag.
178         isEarlyClobber = MI->getOperand(DefIdx).isEarlyClobber();
179       }
180       UseIdx = Indexes->getInstructionIndex(MI).getRegSlot(isEarlyClobber);
181     }
182
183     // MI is reading Reg. We may have visited MI before if it happens to be
184     // reading Reg multiple times. That is OK, extend() is idempotent.
185     extend(LR, UseIdx, Reg);
186   }
187 }
188
189
190 void LiveRangeCalc::updateFromLiveIns() {
191   LiveRangeUpdater Updater;
192   for (const LiveInBlock &I : LiveIn) {
193     if (!I.DomNode)
194       continue;
195     MachineBasicBlock *MBB = I.DomNode->getBlock();
196     assert(I.Value && "No live-in value found");
197     SlotIndex Start, End;
198     std::tie(Start, End) = Indexes->getMBBRange(MBB);
199
200     if (I.Kill.isValid())
201       // Value is killed inside this block.
202       End = I.Kill;
203     else {
204       // The value is live-through, update LiveOut as well.
205       // Defer the Domtree lookup until it is needed.
206       assert(Seen.test(MBB->getNumber()));
207       Map[MBB] = LiveOutPair(I.Value, nullptr);
208     }
209     Updater.setDest(&I.LR);
210     Updater.add(Start, End, I.Value);
211   }
212   LiveIn.clear();
213 }
214
215
216 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg) {
217   assert(Kill.isValid() && "Invalid SlotIndex");
218   assert(Indexes && "Missing SlotIndexes");
219   assert(DomTree && "Missing dominator tree");
220
221   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
222   assert(KillMBB && "No MBB at Kill");
223
224   // Is there a def in the same MBB we can extend?
225   if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
226     return;
227
228   // Find the single reaching def, or determine if Kill is jointly dominated by
229   // multiple values, and we may need to create even more phi-defs to preserve
230   // VNInfo SSA form.  Perform a search for all predecessor blocks where we
231   // know the dominating VNInfo.
232   if (findReachingDefs(LR, *KillMBB, Kill, PhysReg))
233     return;
234
235   // When there were multiple different values, we may need new PHIs.
236   calculateValues();
237 }
238
239
240 // This function is called by a client after using the low-level API to add
241 // live-out and live-in blocks.  The unique value optimization is not
242 // available, SplitEditor::transferValues handles that case directly anyway.
243 void LiveRangeCalc::calculateValues() {
244   assert(Indexes && "Missing SlotIndexes");
245   assert(DomTree && "Missing dominator tree");
246   updateSSA();
247   updateFromLiveIns();
248 }
249
250
251 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
252                                      SlotIndex Kill, unsigned PhysReg) {
253   unsigned KillMBBNum = KillMBB.getNumber();
254
255   // Block numbers where LR should be live-in.
256   SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
257
258   // Remember if we have seen more than one value.
259   bool UniqueVNI = true;
260   VNInfo *TheVNI = nullptr;
261
262   // Using Seen as a visited set, perform a BFS for all reaching defs.
263   for (unsigned i = 0; i != WorkList.size(); ++i) {
264     MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
265
266 #ifndef NDEBUG
267     if (MBB->pred_empty()) {
268       MBB->getParent()->verify();
269       llvm_unreachable("Use not jointly dominated by defs.");
270     }
271
272     if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
273         !MBB->isLiveIn(PhysReg)) {
274       MBB->getParent()->verify();
275       errs() << "The register needs to be live in to BB#" << MBB->getNumber()
276              << ", but is missing from the live-in list.\n";
277       llvm_unreachable("Invalid global physical register");
278     }
279 #endif
280
281     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
282          PE = MBB->pred_end(); PI != PE; ++PI) {
283        MachineBasicBlock *Pred = *PI;
284
285        // Is this a known live-out block?
286        if (Seen.test(Pred->getNumber())) {
287          if (VNInfo *VNI = Map[Pred].first) {
288            if (TheVNI && TheVNI != VNI)
289              UniqueVNI = false;
290            TheVNI = VNI;
291          }
292          continue;
293        }
294
295        SlotIndex Start, End;
296        std::tie(Start, End) = Indexes->getMBBRange(Pred);
297
298        // First time we see Pred.  Try to determine the live-out value, but set
299        // it as null if Pred is live-through with an unknown value.
300        VNInfo *VNI = LR.extendInBlock(Start, End);
301        setLiveOutValue(Pred, VNI);
302        if (VNI) {
303          if (TheVNI && TheVNI != VNI)
304            UniqueVNI = false;
305          TheVNI = VNI;
306          continue;
307        }
308
309        // No, we need a live-in value for Pred as well
310        if (Pred != &KillMBB)
311           WorkList.push_back(Pred->getNumber());
312        else
313           // Loopback to KillMBB, so value is really live through.
314          Kill = SlotIndex();
315     }
316   }
317
318   LiveIn.clear();
319
320   // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
321   // neither require it. Skip the sorting overhead for small updates.
322   if (WorkList.size() > 4)
323     array_pod_sort(WorkList.begin(), WorkList.end());
324
325   // If a unique reaching def was found, blit in the live ranges immediately.
326   if (UniqueVNI) {
327     LiveRangeUpdater Updater(&LR);
328     for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
329          E = WorkList.end(); I != E; ++I) {
330        SlotIndex Start, End;
331        std::tie(Start, End) = Indexes->getMBBRange(*I);
332        // Trim the live range in KillMBB.
333        if (*I == KillMBBNum && Kill.isValid())
334          End = Kill;
335        else
336          Map[MF->getBlockNumbered(*I)] = LiveOutPair(TheVNI, nullptr);
337        Updater.add(Start, End, TheVNI);
338     }
339     return true;
340   }
341
342   // Multiple values were found, so transfer the work list to the LiveIn array
343   // where UpdateSSA will use it as a work list.
344   LiveIn.reserve(WorkList.size());
345   for (SmallVectorImpl<unsigned>::const_iterator
346        I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
347     MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
348     addLiveInBlock(LR, DomTree->getNode(MBB));
349     if (MBB == &KillMBB)
350       LiveIn.back().Kill = Kill;
351   }
352
353   return false;
354 }
355
356
357 // This is essentially the same iterative algorithm that SSAUpdater uses,
358 // except we already have a dominator tree, so we don't have to recompute it.
359 void LiveRangeCalc::updateSSA() {
360   assert(Indexes && "Missing SlotIndexes");
361   assert(DomTree && "Missing dominator tree");
362
363   // Interate until convergence.
364   unsigned Changes;
365   do {
366     Changes = 0;
367     // Propagate live-out values down the dominator tree, inserting phi-defs
368     // when necessary.
369     for (LiveInBlock &I : LiveIn) {
370       MachineDomTreeNode *Node = I.DomNode;
371       // Skip block if the live-in value has already been determined.
372       if (!Node)
373         continue;
374       MachineBasicBlock *MBB = Node->getBlock();
375       MachineDomTreeNode *IDom = Node->getIDom();
376       LiveOutPair IDomValue;
377
378       // We need a live-in value to a block with no immediate dominator?
379       // This is probably an unreachable block that has survived somehow.
380       bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
381
382       // IDom dominates all of our predecessors, but it may not be their
383       // immediate dominator. Check if any of them have live-out values that are
384       // properly dominated by IDom. If so, we need a phi-def here.
385       if (!needPHI) {
386         IDomValue = Map[IDom->getBlock()];
387
388         // Cache the DomTree node that defined the value.
389         if (IDomValue.first && !IDomValue.second)
390           Map[IDom->getBlock()].second = IDomValue.second =
391             DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
392
393         for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
394                PE = MBB->pred_end(); PI != PE; ++PI) {
395           LiveOutPair &Value = Map[*PI];
396           if (!Value.first || Value.first == IDomValue.first)
397             continue;
398
399           // Cache the DomTree node that defined the value.
400           if (!Value.second)
401             Value.second =
402               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
403
404           // This predecessor is carrying something other than IDomValue.
405           // It could be because IDomValue hasn't propagated yet, or it could be
406           // because MBB is in the dominance frontier of that value.
407           if (DomTree->dominates(IDom, Value.second)) {
408             needPHI = true;
409             break;
410           }
411         }
412       }
413
414       // The value may be live-through even if Kill is set, as can happen when
415       // we are called from extendRange. In that case LiveOutSeen is true, and
416       // LiveOut indicates a foreign or missing value.
417       LiveOutPair &LOP = Map[MBB];
418
419       // Create a phi-def if required.
420       if (needPHI) {
421         ++Changes;
422         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
423         SlotIndex Start, End;
424         std::tie(Start, End) = Indexes->getMBBRange(MBB);
425         LiveRange &LR = I.LR;
426         VNInfo *VNI = LR.getNextValue(Start, *Alloc);
427         I.Value = VNI;
428         // This block is done, we know the final value.
429         I.DomNode = nullptr;
430
431         // Add liveness since updateFromLiveIns now skips this node.
432         if (I.Kill.isValid())
433           LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
434         else {
435           LR.addSegment(LiveInterval::Segment(Start, End, VNI));
436           LOP = LiveOutPair(VNI, Node);
437         }
438       } else if (IDomValue.first) {
439         // No phi-def here. Remember incoming value.
440         I.Value = IDomValue.first;
441
442         // If the IDomValue is killed in the block, don't propagate through.
443         if (I.Kill.isValid())
444           continue;
445
446         // Propagate IDomValue if it isn't killed:
447         // MBB is live-out and doesn't define its own value.
448         if (LOP.first == IDomValue.first)
449           continue;
450         ++Changes;
451         LOP = IDomValue;
452       }
453     }
454   } while (Changes);
455 }