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,
133 assert(LI && "Missing live range");
134 assert(Kill.isValid() && "Invalid SlotIndex");
135 assert(Indexes && "Missing SlotIndexes");
136 assert(DomTree && "Missing dominator tree");
138 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
139 assert(KillMBB && "No MBB at Kill");
141 // Is there a def in the same MBB we can extend?
142 if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
145 // Find the single reaching def, or determine if Kill is jointly dominated by
146 // multiple values, and we may need to create even more phi-defs to preserve
147 // VNInfo SSA form. Perform a search for all predecessor blocks where we
148 // know the dominating VNInfo.
149 VNInfo *VNI = findReachingDefs(LI, KillMBB, Kill);
151 // When there were multiple different values, we may need new PHIs.
159 // This function is called by a client after using the low-level API to add
160 // live-out and live-in blocks. The unique value optimization is not
161 // available, SplitEditor::transferValues handles that case directly anyway.
162 void LiveRangeCalc::calculateValues() {
163 assert(Indexes && "Missing SlotIndexes");
164 assert(DomTree && "Missing dominator tree");
170 VNInfo *LiveRangeCalc::findReachingDefs(LiveInterval *LI,
171 MachineBasicBlock *KillMBB,
173 // Blocks where LI should be live-in.
174 SmallVector<MachineBasicBlock*, 16> WorkList(1, KillMBB);
176 // Remember if we have seen more than one value.
177 bool UniqueVNI = true;
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 = WorkList[i];
183 assert(!MBB->pred_empty() && "Value live-in to entry block?");
184 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
185 PE = MBB->pred_end(); PI != PE; ++PI) {
186 MachineBasicBlock *Pred = *PI;
188 // Is this a known live-out block?
189 if (Seen.test(Pred->getNumber())) {
190 if (VNInfo *VNI = LiveOut[Pred].first) {
191 if (TheVNI && TheVNI != VNI)
198 SlotIndex Start, End;
199 tie(Start, End) = Indexes->getMBBRange(Pred);
201 // First time we see Pred. Try to determine the live-out value, but set
202 // it as null if Pred is live-through with an unknown value.
203 VNInfo *VNI = LI->extendInBlock(Start, End);
204 setLiveOutValue(Pred, VNI);
206 if (TheVNI && TheVNI != VNI)
212 // No, we need a live-in value for Pred as well
214 WorkList.push_back(Pred);
216 // Loopback to KillMBB, so value is really live through.
221 // Transfer WorkList to LiveInBlocks in reverse order.
222 // This ordering works best with updateSSA().
224 LiveIn.reserve(WorkList.size());
225 while(!WorkList.empty())
226 addLiveInBlock(LI, DomTree->getNode(WorkList.pop_back_val()));
228 // The kill block may not be live-through.
229 assert(LiveIn.back().DomNode->getBlock() == KillMBB);
230 LiveIn.back().Kill = Kill;
232 return UniqueVNI ? TheVNI : 0;
236 // This is essentially the same iterative algorithm that SSAUpdater uses,
237 // except we already have a dominator tree, so we don't have to recompute it.
238 void LiveRangeCalc::updateSSA() {
239 assert(Indexes && "Missing SlotIndexes");
240 assert(DomTree && "Missing dominator tree");
242 // Interate until convergence.
246 // Propagate live-out values down the dominator tree, inserting phi-defs
248 for (SmallVectorImpl<LiveInBlock>::iterator I = LiveIn.begin(),
249 E = LiveIn.end(); I != E; ++I) {
250 MachineDomTreeNode *Node = I->DomNode;
251 // Skip block if the live-in value has already been determined.
254 MachineBasicBlock *MBB = Node->getBlock();
255 MachineDomTreeNode *IDom = Node->getIDom();
256 LiveOutPair IDomValue;
258 // We need a live-in value to a block with no immediate dominator?
259 // This is probably an unreachable block that has survived somehow.
260 bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
262 // IDom dominates all of our predecessors, but it may not be their
263 // immediate dominator. Check if any of them have live-out values that are
264 // properly dominated by IDom. If so, we need a phi-def here.
266 IDomValue = LiveOut[IDom->getBlock()];
268 // Cache the DomTree node that defined the value.
269 if (IDomValue.first && !IDomValue.second)
270 LiveOut[IDom->getBlock()].second = IDomValue.second =
271 DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
273 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
274 PE = MBB->pred_end(); PI != PE; ++PI) {
275 LiveOutPair &Value = LiveOut[*PI];
276 if (!Value.first || Value.first == IDomValue.first)
279 // Cache the DomTree node that defined the value.
282 DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
284 // This predecessor is carrying something other than IDomValue.
285 // It could be because IDomValue hasn't propagated yet, or it could be
286 // because MBB is in the dominance frontier of that value.
287 if (DomTree->dominates(IDom, Value.second)) {
294 // The value may be live-through even if Kill is set, as can happen when
295 // we are called from extendRange. In that case LiveOutSeen is true, and
296 // LiveOut indicates a foreign or missing value.
297 LiveOutPair &LOP = LiveOut[MBB];
299 // Create a phi-def if required.
302 assert(Alloc && "Need VNInfo allocator to create PHI-defs");
303 SlotIndex Start, End;
304 tie(Start, End) = Indexes->getMBBRange(MBB);
305 VNInfo *VNI = I->LI->getNextValue(Start, *Alloc);
306 VNI->setIsPHIDef(true);
308 // This block is done, we know the final value.
311 // Add liveness since updateLiveIns now skips this node.
312 if (I->Kill.isValid())
313 I->LI->addRange(LiveRange(Start, I->Kill, VNI));
315 I->LI->addRange(LiveRange(Start, End, VNI));
316 LOP = LiveOutPair(VNI, Node);
318 } else if (IDomValue.first) {
319 // No phi-def here. Remember incoming value.
320 I->Value = IDomValue.first;
322 // If the IDomValue is killed in the block, don't propagate through.
323 if (I->Kill.isValid())
326 // Propagate IDomValue if it isn't killed:
327 // MBB is live-out and doesn't define its own value.
328 if (LOP.first == IDomValue.first)