Be more verbose when detecting dominance problems.
[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 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeCalc.h"
16 #include "llvm/CodeGen/MachineDominators.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18
19 using namespace llvm;
20
21 void LiveRangeCalc::reset(const MachineFunction *MF,
22                           SlotIndexes *SI,
23                           MachineDominatorTree *MDT,
24                           VNInfo::Allocator *VNIA) {
25   MRI = &MF->getRegInfo();
26   Indexes = SI;
27   DomTree = MDT;
28   Alloc = VNIA;
29
30   unsigned N = MF->getNumBlockIDs();
31   Seen.clear();
32   Seen.resize(N);
33   LiveOut.resize(N);
34   LiveIn.clear();
35 }
36
37
38 void LiveRangeCalc::createDeadDefs(LiveInterval *LI, unsigned Reg) {
39   assert(MRI && Indexes && "call reset() first");
40
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.
47     SlotIndex Idx;
48     if (MI->isPHI())
49       // PHI defs begin at the basic block start index.
50       Idx = Indexes->getMBBStartIdx(MI->getParent());
51     else
52       // Instructions are either normal 'r', or early clobber 'e'.
53       Idx = Indexes->getInstructionIndex(MI)
54         .getRegSlot(I.getOperand().isEarlyClobber());
55
56     // Create the def in LI. This may find an existing def.
57     VNInfo *VNI = LI->createDeadDef(Idx, *Alloc);
58     VNI->setIsPHIDef(MI->isPHI());
59   }
60 }
61
62
63 void LiveRangeCalc::extendToUses(LiveInterval *LI, unsigned Reg) {
64   assert(MRI && Indexes && "call reset() first");
65
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();
70     if (!MO.readsReg())
71       continue;
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;
75
76     // Find the SlotIndex being read.
77     SlotIndex Idx;
78     if (MI->isPHI()) {
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());
83     } else {
84       // This is a normal instruction.
85       Idx = Indexes->getInstructionIndex(MI).getRegSlot();
86       // Check for early-clobber redefs.
87       unsigned DefIdx;
88       if (MO.isDef()) {
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);
96       }
97     }
98     extend(LI, Idx, Reg);
99   }
100 }
101
102
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) {
107     if (!I->DomNode)
108       continue;
109     MachineBasicBlock *MBB = I->DomNode->getBlock();
110
111     VNInfo *VNI = OverrideVNI ? OverrideVNI : I->Value;
112     assert(VNI && "No live-in value found");
113
114     SlotIndex Start, End;
115     tie(Start, End) = Indexes->getMBBRange(MBB);
116
117     if (I->Kill.isValid())
118       I->LI->addRange(LiveRange(Start, I->Kill, VNI));
119     else {
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);
125     }
126   }
127   LiveIn.clear();
128 }
129
130
131 void LiveRangeCalc::extend(LiveInterval *LI,
132                            SlotIndex Kill,
133                            unsigned PhysReg) {
134   assert(LI && "Missing live range");
135   assert(Kill.isValid() && "Invalid SlotIndex");
136   assert(Indexes && "Missing SlotIndexes");
137   assert(DomTree && "Missing dominator tree");
138
139   MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill.getPrevSlot());
140   assert(KillMBB && "No MBB at Kill");
141
142   // Is there a def in the same MBB we can extend?
143   if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
144     return;
145
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);
151
152   // When there were multiple different values, we may need new PHIs.
153   if (!VNI)
154     updateSSA();
155
156   updateLiveIns(VNI);
157 }
158
159
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");
166   updateSSA();
167   updateLiveIns(0);
168 }
169
170
171 VNInfo *LiveRangeCalc::findReachingDefs(LiveInterval *LI,
172                                         MachineBasicBlock *KillMBB,
173                                         SlotIndex Kill,
174                                         unsigned PhysReg) {
175   // Blocks where LI should be live-in.
176   SmallVector<MachineBasicBlock*, 16> WorkList(1, KillMBB);
177
178   // Remember if we have seen more than one value.
179   bool UniqueVNI = true;
180   VNInfo *TheVNI = 0;
181
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];
185
186 #ifndef NDEBUG
187     if (MBB->pred_empty()) {
188       MBB->getParent()->verify();
189       llvm_unreachable("Use not jointly dominated by defs.");
190     }
191
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");
198     }
199 #endif
200
201     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
202            PE = MBB->pred_end(); PI != PE; ++PI) {
203        MachineBasicBlock *Pred = *PI;
204
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)
209              UniqueVNI = false;
210            TheVNI = VNI;
211          }
212          continue;
213        }
214
215        SlotIndex Start, End;
216        tie(Start, End) = Indexes->getMBBRange(Pred);
217
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);
222        if (VNI) {
223          if (TheVNI && TheVNI != VNI)
224            UniqueVNI = false;
225          TheVNI = VNI;
226          continue;
227        }
228
229        // No, we need a live-in value for Pred as well
230        if (Pred != KillMBB)
231           WorkList.push_back(Pred);
232        else
233           // Loopback to KillMBB, so value is really live through.
234          Kill = SlotIndex();
235     }
236   }
237
238   // Transfer WorkList to LiveInBlocks in reverse order.
239   // This ordering works best with updateSSA().
240   LiveIn.clear();
241   LiveIn.reserve(WorkList.size());
242   while(!WorkList.empty())
243     addLiveInBlock(LI, DomTree->getNode(WorkList.pop_back_val()));
244
245   // The kill block may not be live-through.
246   assert(LiveIn.back().DomNode->getBlock() == KillMBB);
247   LiveIn.back().Kill = Kill;
248
249   return UniqueVNI ? TheVNI : 0;
250 }
251
252
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");
258
259   // Interate until convergence.
260   unsigned Changes;
261   do {
262     Changes = 0;
263     // Propagate live-out values down the dominator tree, inserting phi-defs
264     // when necessary.
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.
269       if (!Node)
270         continue;
271       MachineBasicBlock *MBB = Node->getBlock();
272       MachineDomTreeNode *IDom = Node->getIDom();
273       LiveOutPair IDomValue;
274
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());
278
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.
282       if (!needPHI) {
283         IDomValue = LiveOut[IDom->getBlock()];
284
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));
289
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)
294             continue;
295
296           // Cache the DomTree node that defined the value.
297           if (!Value.second)
298             Value.second =
299               DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
300
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)) {
305             needPHI = true;
306             break;
307           }
308         }
309       }
310
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];
315
316       // Create a phi-def if required.
317       if (needPHI) {
318         ++Changes;
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);
324         I->Value = VNI;
325         // This block is done, we know the final value.
326         I->DomNode = 0;
327
328         // Add liveness since updateLiveIns now skips this node.
329         if (I->Kill.isValid())
330           I->LI->addRange(LiveRange(Start, I->Kill, VNI));
331         else {
332           I->LI->addRange(LiveRange(Start, End, VNI));
333           LOP = LiveOutPair(VNI, Node);
334         }
335       } else if (IDomValue.first) {
336         // No phi-def here. Remember incoming value.
337         I->Value = IDomValue.first;
338
339         // If the IDomValue is killed in the block, don't propagate through.
340         if (I->Kill.isValid())
341           continue;
342
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)
346           continue;
347         ++Changes;
348         LOP = IDomValue;
349       }
350     }
351   } while (Changes);
352 }