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 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeCalc.h"
16 #include "llvm/CodeGen/MachineDominators.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 void LiveRangeCalc::reset(const MachineFunction *MF,
23 MachineDominatorTree *MDT,
24 VNInfo::Allocator *VNIA) {
25 MRI = &MF->getRegInfo();
30 unsigned N = MF->getNumBlockIDs();
38 void LiveRangeCalc::createDeadDefs(LiveInterval *LI, unsigned Reg) {
39 assert(MRI && Indexes && "call reset() first");
41 // Visit all def operands. If the same instruction has multiple defs of Reg,
42 // LI->createDeadDef() will deduplicate.
43 for (MachineRegisterInfo::def_iterator
44 I = MRI->def_begin(Reg), E = MRI->def_end(); I != E; ++I) {
45 const MachineInstr *MI = &*I;
46 // Find the corresponding slot index.
49 // PHI defs begin at the basic block start index.
50 Idx = Indexes->getMBBStartIdx(MI->getParent());
52 // Instructions are either normal 'r', or early clobber 'e'.
53 Idx = Indexes->getInstructionIndex(MI)
54 .getRegSlot(I.getOperand().isEarlyClobber());
56 // Create the def in LI. This may find an existing def.
57 VNInfo *VNI = LI->createDeadDef(Idx, *Alloc);
58 VNI->setIsPHIDef(MI->isPHI());
63 void LiveRangeCalc::extendToUses(LiveInterval *LI, unsigned Reg) {
64 assert(MRI && Indexes && "call reset() first");
66 // Visit all operands that read Reg. This may include partial defs.
67 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(Reg),
68 E = MRI->reg_nodbg_end(); I != E; ++I) {
69 const MachineOperand &MO = I.getOperand();
72 // MI is reading Reg. We may have visited MI before if it happens to be
73 // reading Reg multiple times. That is OK, extend() is idempotent.
74 const MachineInstr *MI = &*I;
76 // Find the SlotIndex being read.
79 assert(!MO.isDef() && "Cannot handle PHI def of partial register.");
80 // PHI operands are paired: (Reg, PredMBB).
81 // Extend the live range to be live-out from PredMBB.
82 Idx = Indexes->getMBBEndIdx(MI->getOperand(I.getOperandNo()+1).getMBB());
84 // This is a normal instruction.
85 Idx = Indexes->getInstructionIndex(MI).getRegSlot();
86 // Check for early-clobber redefs.
89 if (MO.isEarlyClobber())
90 Idx = Idx.getRegSlot(true);
91 } else if (MI->isRegTiedToDefOperand(I.getOperandNo(), &DefIdx)) {
92 // FIXME: This would be a lot easier if tied early-clobber uses also
93 // had an early-clobber flag.
94 if (MI->getOperand(DefIdx).isEarlyClobber())
95 Idx = Idx.getRegSlot(true);
103 // Transfer information from the LiveIn vector to the live ranges.
104 void LiveRangeCalc::updateLiveIns(VNInfo *OverrideVNI) {
105 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
106 E = LiveIn.end(); I != E; ++I) {
109 MachineBasicBlock *MBB = I->DomNode->getBlock();
111 VNInfo *VNI = OverrideVNI ? OverrideVNI : I->Value;
112 assert(VNI && "No live-in value found");
114 SlotIndex Start, End;
115 tie(Start, End) = Indexes->getMBBRange(MBB);
117 if (I->Kill.isValid())
118 I->LI->addRange(LiveRange(Start, I->Kill, VNI));
120 I->LI->addRange(LiveRange(Start, End, VNI));
121 // The value is live-through, update LiveOut as well. Defer the Domtree
122 // lookup until it is needed.
123 assert(Seen.test(MBB->getNumber()));
124 LiveOut[MBB] = LiveOutPair(VNI, (MachineDomTreeNode *)0);
131 void LiveRangeCalc::extend(LiveInterval *LI,
134 assert(LI && "Missing live range");
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 (LI->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 VNInfo *VNI = findReachingDefs(LI, KillMBB, Kill, PhysReg);
152 // When there were multiple different values, we may need new PHIs.
160 // This function is called by a client after using the low-level API to add
161 // live-out and live-in blocks. The unique value optimization is not
162 // available, SplitEditor::transferValues handles that case directly anyway.
163 void LiveRangeCalc::calculateValues() {
164 assert(Indexes && "Missing SlotIndexes");
165 assert(DomTree && "Missing dominator tree");
171 VNInfo *LiveRangeCalc::findReachingDefs(LiveInterval *LI,
172 MachineBasicBlock *KillMBB,
175 // Blocks where LI should be live-in.
176 SmallVector<MachineBasicBlock*, 16> WorkList(1, KillMBB);
178 // Remember if we have seen more than one value.
179 bool UniqueVNI = true;
182 // Using Seen as a visited set, perform a BFS for all reaching defs.
183 for (unsigned i = 0; i != WorkList.size(); ++i) {
184 MachineBasicBlock *MBB = WorkList[i];
187 if (MBB->pred_empty()) {
188 MBB->getParent()->verify();
189 llvm_unreachable("Use not jointly dominated by defs.");
192 if (TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
193 !MBB->isLiveIn(PhysReg)) {
194 MBB->getParent()->verify();
195 errs() << "The register needs to be live in to BB#" << MBB->getNumber()
196 << ", but is missing from the live-in list.\n";
197 llvm_unreachable("Invalid global physical register");
201 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
202 PE = MBB->pred_end(); PI != PE; ++PI) {
203 MachineBasicBlock *Pred = *PI;
205 // Is this a known live-out block?
206 if (Seen.test(Pred->getNumber())) {
207 if (VNInfo *VNI = LiveOut[Pred].first) {
208 if (TheVNI && TheVNI != VNI)
215 SlotIndex Start, End;
216 tie(Start, End) = Indexes->getMBBRange(Pred);
218 // First time we see Pred. Try to determine the live-out value, but set
219 // it as null if Pred is live-through with an unknown value.
220 VNInfo *VNI = LI->extendInBlock(Start, End);
221 setLiveOutValue(Pred, VNI);
223 if (TheVNI && TheVNI != VNI)
229 // No, we need a live-in value for Pred as well
231 WorkList.push_back(Pred);
233 // Loopback to KillMBB, so value is really live through.
238 // Transfer WorkList to LiveInBlocks in reverse order.
239 // This ordering works best with updateSSA().
241 LiveIn.reserve(WorkList.size());
242 while(!WorkList.empty())
243 addLiveInBlock(LI, DomTree->getNode(WorkList.pop_back_val()));
245 // The kill block may not be live-through.
246 assert(LiveIn.back().DomNode->getBlock() == KillMBB);
247 LiveIn.back().Kill = Kill;
249 return UniqueVNI ? TheVNI : 0;
253 // This is essentially the same iterative algorithm that SSAUpdater uses,
254 // except we already have a dominator tree, so we don't have to recompute it.
255 void LiveRangeCalc::updateSSA() {
256 assert(Indexes && "Missing SlotIndexes");
257 assert(DomTree && "Missing dominator tree");
259 // Interate until convergence.
263 // Propagate live-out values down the dominator tree, inserting phi-defs
265 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
266 E = LiveIn.end(); I != E; ++I) {
267 MachineDomTreeNode *Node = I->DomNode;
268 // Skip block if the live-in value has already been determined.
271 MachineBasicBlock *MBB = Node->getBlock();
272 MachineDomTreeNode *IDom = Node->getIDom();
273 LiveOutPair IDomValue;
275 // We need a live-in value to a block with no immediate dominator?
276 // This is probably an unreachable block that has survived somehow.
277 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
279 // IDom dominates all of our predecessors, but it may not be their
280 // immediate dominator. Check if any of them have live-out values that are
281 // properly dominated by IDom. If so, we need a phi-def here.
283 IDomValue = LiveOut[IDom->getBlock()];
285 // Cache the DomTree node that defined the value.
286 if (IDomValue.first && !IDomValue.second)
287 LiveOut[IDom->getBlock()].second = IDomValue.second =
288 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
290 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
291 PE = MBB->pred_end(); PI != PE; ++PI) {
292 LiveOutPair &Value = LiveOut[*PI];
293 if (!Value.first || Value.first == IDomValue.first)
296 // Cache the DomTree node that defined the value.
299 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
301 // This predecessor is carrying something other than IDomValue.
302 // It could be because IDomValue hasn't propagated yet, or it could be
303 // because MBB is in the dominance frontier of that value.
304 if (DomTree->dominates(IDom, Value.second)) {
311 // The value may be live-through even if Kill is set, as can happen when
312 // we are called from extendRange. In that case LiveOutSeen is true, and
313 // LiveOut indicates a foreign or missing value.
314 LiveOutPair &LOP = LiveOut[MBB];
316 // Create a phi-def if required.
319 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
320 SlotIndex Start, End;
321 tie(Start, End) = Indexes->getMBBRange(MBB);
322 VNInfo *VNI = I->LI->getNextValue(Start, *Alloc);
323 VNI->setIsPHIDef(true);
325 // This block is done, we know the final value.
328 // Add liveness since updateLiveIns now skips this node.
329 if (I->Kill.isValid())
330 I->LI->addRange(LiveRange(Start, I->Kill, VNI));
332 I->LI->addRange(LiveRange(Start, End, VNI));
333 LOP = LiveOutPair(VNI, Node);
335 } else if (IDomValue.first) {
336 // No phi-def here. Remember incoming value.
337 I->Value = IDomValue.first;
339 // If the IDomValue is killed in the block, don't propagate through.
340 if (I->Kill.isValid())
343 // Propagate IDomValue if it isn't killed:
344 // MBB is live-out and doesn't define its own value.
345 if (LOP.first == IDomValue.first)