1 //===---- LiveRangeCalc.cpp - Calculate live ranges -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the LiveRangeCalc class.
12 //===----------------------------------------------------------------------===//
14 #include "LiveRangeCalc.h"
15 #include "llvm/CodeGen/MachineDominators.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #define DEBUG_TYPE "regalloc"
22 void LiveRangeCalc::reset(const MachineFunction *mf,
24 MachineDominatorTree *MDT,
25 VNInfo::Allocator *VNIA) {
27 MRI = &MF->getRegInfo();
32 unsigned N = MF->getNumBlockIDs();
40 void LiveRangeCalc::createDeadDefs(LiveRange &LR, unsigned Reg) {
41 assert(MRI && Indexes && "call reset() first");
43 // Visit all def operands. If the same instruction has multiple defs of Reg,
44 // LR.createDeadDef() will deduplicate.
45 for (MachineOperand &MO : MRI->def_operands(Reg)) {
46 const MachineInstr *MI = MO.getParent();
47 // Find the corresponding slot index.
50 // PHI defs begin at the basic block start index.
51 Idx = Indexes->getMBBStartIdx(MI->getParent());
53 // Instructions are either normal 'r', or early clobber 'e'.
54 Idx = Indexes->getInstructionIndex(MI)
55 .getRegSlot(MO.isEarlyClobber());
57 // Create the def in LR. This may find an existing def.
58 LR.createDeadDef(Idx, *Alloc);
63 void LiveRangeCalc::extendToUses(LiveRange &LR, unsigned Reg) {
64 assert(MRI && Indexes && "call reset() first");
66 // Visit all operands that read Reg. This may include partial defs.
67 for (MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
68 // Clear all kill flags. They will be reinserted after register allocation
69 // by LiveIntervalAnalysis::addKillFlags().
74 // MI is reading Reg. We may have visited MI before if it happens to be
75 // reading Reg multiple times. That is OK, extend() is idempotent.
76 const MachineInstr *MI = MO.getParent();
77 unsigned OpNo = (&MO - &MI->getOperand(0));
79 // Find the SlotIndex being read.
82 assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
83 // PHI operands are paired: (Reg, PredMBB).
84 // Extend the live range to be live-out from PredMBB.
85 Idx = Indexes->getMBBEndIdx(MI->getOperand(OpNo+1).getMBB());
87 // This is a normal instruction.
88 Idx = Indexes->getInstructionIndex(MI).getRegSlot();
89 // Check for early-clobber redefs.
92 if (MO.isEarlyClobber())
93 Idx = Idx.getRegSlot(true);
94 } else if (MI->isRegTiedToDefOperand(OpNo, &DefIdx)) {
95 // FIXME: This would be a lot easier if tied early-clobber uses also
96 // had an early-clobber flag.
97 if (MI->getOperand(DefIdx).isEarlyClobber())
98 Idx = Idx.getRegSlot(true);
101 extend(LR, Idx, Reg);
106 // Transfer information from the LiveIn vector to the live ranges.
107 void LiveRangeCalc::updateLiveIns() {
108 LiveRangeUpdater Updater;
109 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
110 E = LiveIn.end(); I != E; ++I) {
113 MachineBasicBlock *MBB = I->DomNode->getBlock();
114 assert(I->Value && "No live-in value found");
115 SlotIndex Start, End;
116 std::tie(Start, End) = Indexes->getMBBRange(MBB);
118 if (I->Kill.isValid())
119 // Value is killed inside this block.
122 // The value is live-through, update LiveOut as well.
123 // Defer the Domtree lookup until it is needed.
124 assert(Seen.test(MBB->getNumber()));
125 LiveOut[MBB] = LiveOutPair(I->Value, (MachineDomTreeNode *)nullptr);
127 Updater.setDest(&I->LR);
128 Updater.add(Start, End, I->Value);
134 void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Kill, unsigned PhysReg) {
135 assert(Kill.isValid() && "Invalid SlotIndex");
136 assert(Indexes && "Missing SlotIndexes");
137 assert(DomTree && "Missing dominator tree");
139 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
140 assert(KillMBB && "No MBB at Kill");
142 // Is there a def in the same MBB we can extend?
143 if (LR.extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
146 // Find the single reaching def, or determine if Kill is jointly dominated by
147 // multiple values, and we may need to create even more phi-defs to preserve
148 // VNInfo SSA form. Perform a search for all predecessor blocks where we
149 // know the dominating VNInfo.
150 if (findReachingDefs(LR, *KillMBB, Kill, PhysReg))
153 // When there were multiple different values, we may need new PHIs.
158 // This function is called by a client after using the low-level API to add
159 // live-out and live-in blocks. The unique value optimization is not
160 // available, SplitEditor::transferValues handles that case directly anyway.
161 void LiveRangeCalc::calculateValues() {
162 assert(Indexes && "Missing SlotIndexes");
163 assert(DomTree && "Missing dominator tree");
169 bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &KillMBB,
170 SlotIndex Kill, unsigned PhysReg) {
171 unsigned KillMBBNum = KillMBB.getNumber();
173 // Block numbers where LR should be live-in.
174 SmallVector<unsigned, 16> WorkList(1, KillMBBNum);
176 // Remember if we have seen more than one value.
177 bool UniqueVNI = true;
178 VNInfo *TheVNI = nullptr;
180 // Using Seen as a visited set, perform a BFS for all reaching defs.
181 for (unsigned i = 0; i != WorkList.size(); ++i) {
182 MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
185 if (MBB->pred_empty()) {
186 MBB->getParent()->verify();
187 llvm_unreachable("Use not jointly dominated by defs.");
190 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
191 !MBB->isLiveIn(PhysReg)) {
192 MBB->getParent()->verify();
193 errs() << "The register needs to be live in to BB#" << MBB->getNumber()
194 << ", but is missing from the live-in list.\n";
195 llvm_unreachable("Invalid global physical register");
199 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
200 PE = MBB->pred_end(); PI != PE; ++PI) {
201 MachineBasicBlock *Pred = *PI;
203 // Is this a known live-out block?
204 if (Seen.test(Pred->getNumber())) {
205 if (VNInfo *VNI = LiveOut[Pred].first) {
206 if (TheVNI && TheVNI != VNI)
213 SlotIndex Start, End;
214 std::tie(Start, End) = Indexes->getMBBRange(Pred);
216 // First time we see Pred. Try to determine the live-out value, but set
217 // it as null if Pred is live-through with an unknown value.
218 VNInfo *VNI = LR.extendInBlock(Start, End);
219 setLiveOutValue(Pred, VNI);
221 if (TheVNI && TheVNI != VNI)
227 // No, we need a live-in value for Pred as well
228 if (Pred != &KillMBB)
229 WorkList.push_back(Pred->getNumber());
231 // Loopback to KillMBB, so value is really live through.
238 // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
239 // neither require it. Skip the sorting overhead for small updates.
240 if (WorkList.size() > 4)
241 array_pod_sort(WorkList.begin(), WorkList.end());
243 // If a unique reaching def was found, blit in the live ranges immediately.
245 LiveRangeUpdater Updater(&LR);
246 for (SmallVectorImpl<unsigned>::const_iterator I = WorkList.begin(),
247 E = WorkList.end(); I != E; ++I) {
248 SlotIndex Start, End;
249 std::tie(Start, End) = Indexes->getMBBRange(*I);
250 // Trim the live range in KillMBB.
251 if (*I == KillMBBNum && Kill.isValid())
254 LiveOut[MF->getBlockNumbered(*I)] =
255 LiveOutPair(TheVNI, nullptr);
256 Updater.add(Start, End, TheVNI);
261 // Multiple values were found, so transfer the work list to the LiveIn array
262 // where UpdateSSA will use it as a work list.
263 LiveIn.reserve(WorkList.size());
264 for (SmallVectorImpl<unsigned>::const_iterator
265 I = WorkList.begin(), E = WorkList.end(); I != E; ++I) {
266 MachineBasicBlock *MBB = MF->getBlockNumbered(*I);
267 addLiveInBlock(LR, DomTree->getNode(MBB));
269 LiveIn.back().Kill = Kill;
276 // This is essentially the same iterative algorithm that SSAUpdater uses,
277 // except we already have a dominator tree, so we don't have to recompute it.
278 void LiveRangeCalc::updateSSA() {
279 assert(Indexes && "Missing SlotIndexes");
280 assert(DomTree && "Missing dominator tree");
282 // Interate until convergence.
286 // Propagate live-out values down the dominator tree, inserting phi-defs
288 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
289 E = LiveIn.end(); I != E; ++I) {
290 MachineDomTreeNode *Node = I->DomNode;
291 // Skip block if the live-in value has already been determined.
294 MachineBasicBlock *MBB = Node->getBlock();
295 MachineDomTreeNode *IDom = Node->getIDom();
296 LiveOutPair IDomValue;
298 // We need a live-in value to a block with no immediate dominator?
299 // This is probably an unreachable block that has survived somehow.
300 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
302 // IDom dominates all of our predecessors, but it may not be their
303 // immediate dominator. Check if any of them have live-out values that are
304 // properly dominated by IDom. If so, we need a phi-def here.
306 IDomValue = LiveOut[IDom->getBlock()];
308 // Cache the DomTree node that defined the value.
309 if (IDomValue.first && !IDomValue.second)
310 LiveOut[IDom->getBlock()].second = IDomValue.second =
311 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
313 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
314 PE = MBB->pred_end(); PI != PE; ++PI) {
315 LiveOutPair &Value = LiveOut[*PI];
316 if (!Value.first || Value.first == IDomValue.first)
319 // Cache the DomTree node that defined the value.
322 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
324 // This predecessor is carrying something other than IDomValue.
325 // It could be because IDomValue hasn't propagated yet, or it could be
326 // because MBB is in the dominance frontier of that value.
327 if (DomTree->dominates(IDom, Value.second)) {
334 // The value may be live-through even if Kill is set, as can happen when
335 // we are called from extendRange. In that case LiveOutSeen is true, and
336 // LiveOut indicates a foreign or missing value.
337 LiveOutPair &LOP = LiveOut[MBB];
339 // Create a phi-def if required.
342 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
343 SlotIndex Start, End;
344 std::tie(Start, End) = Indexes->getMBBRange(MBB);
345 LiveRange &LR = I->LR;
346 VNInfo *VNI = LR.getNextValue(Start, *Alloc);
348 // This block is done, we know the final value.
349 I->DomNode = nullptr;
351 // Add liveness since updateLiveIns now skips this node.
352 if (I->Kill.isValid())
353 LR.addSegment(LiveInterval::Segment(Start, I->Kill, VNI));
355 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
356 LOP = LiveOutPair(VNI, Node);
358 } else if (IDomValue.first) {
359 // No phi-def here. Remember incoming value.
360 I->Value = IDomValue.first;
362 // If the IDomValue is killed in the block, don't propagate through.
363 if (I->Kill.isValid())
366 // Propagate IDomValue if it isn't killed:
367 // MBB is live-out and doesn't define its own value.
368 if (LOP.first == IDomValue.first)