Fix ExpandShiftWithUnknownAmountBit, which was completely bogus.
[oota-llvm.git] / lib / CodeGen / MachineSSAUpdater.cpp
1 //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
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 // This file implements the MachineSSAUpdater class. It's based on SSAUpdater
11 // class in lib/Transforms/Utils.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/MachineSSAUpdater.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 typedef DenseMap<MachineBasicBlock*, unsigned> AvailableValsTy;
29 typedef std::vector<std::pair<MachineBasicBlock*, unsigned> >
30                 IncomingPredInfoTy;
31
32 static AvailableValsTy &getAvailableVals(void *AV) {
33   return *static_cast<AvailableValsTy*>(AV);
34 }
35
36 static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
37   return *static_cast<IncomingPredInfoTy*>(IPI);
38 }
39
40
41 MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
42                                      SmallVectorImpl<MachineInstr*> *NewPHI)
43   : AV(0), IPI(0), InsertedPHIs(NewPHI) {
44   TII = MF.getTarget().getInstrInfo();
45   MRI = &MF.getRegInfo();
46 }
47
48 MachineSSAUpdater::~MachineSSAUpdater() {
49   delete &getAvailableVals(AV);
50   delete &getIncomingPredInfo(IPI);
51 }
52
53 /// Initialize - Reset this object to get ready for a new set of SSA
54 /// updates.  ProtoValue is the value used to name PHI nodes.
55 void MachineSSAUpdater::Initialize(unsigned V) {
56   if (AV == 0)
57     AV = new AvailableValsTy();
58   else
59     getAvailableVals(AV).clear();
60
61   if (IPI == 0)
62     IPI = new IncomingPredInfoTy();
63   else
64     getIncomingPredInfo(IPI).clear();
65
66   VR = V;
67   VRC = MRI->getRegClass(VR);
68 }
69
70 /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
71 /// the specified block.
72 bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
73   return getAvailableVals(AV).count(BB);
74 }
75
76 /// AddAvailableValue - Indicate that a rewritten value is available in the
77 /// specified block with the specified value.
78 void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
79   getAvailableVals(AV)[BB] = V;
80 }
81
82 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
83 /// live at the end of the specified block.
84 unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
85   return GetValueAtEndOfBlockInternal(BB);
86 }
87
88 /// InsertNewPHI - Insert an empty PHI instruction which define a value of the
89 /// given register class at the start of the specified basic block. It returns
90 /// the virtual register defined by the PHI instruction.
91 static
92 MachineInstr *InsertNewPHI(MachineBasicBlock *BB, const TargetRegisterClass *RC,
93                          MachineRegisterInfo *MRI, const TargetInstrInfo *TII) {
94   unsigned NewVR = MRI->createVirtualRegister(RC);
95   return BuildMI(*BB, BB->front(), BB->front().getDebugLoc(),
96                  TII->get(TargetInstrInfo::PHI), NewVR);
97 }
98                           
99
100 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
101 /// is live in the middle of the specified block.
102 ///
103 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
104 /// important case: if there is a definition of the rewritten value after the
105 /// 'use' in BB.  Consider code like this:
106 ///
107 ///      X1 = ...
108 ///   SomeBB:
109 ///      use(X)
110 ///      X2 = ...
111 ///      br Cond, SomeBB, OutBB
112 ///
113 /// In this case, there are two values (X1 and X2) added to the AvailableVals
114 /// set by the client of the rewriter, and those values are both live out of
115 /// their respective blocks.  However, the use of X happens in the *middle* of
116 /// a block.  Because of this, we need to insert a new PHI node in SomeBB to
117 /// merge the appropriate values, and this value isn't live out of the block.
118 ///
119 unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
120   // If there is no definition of the renamed variable in this block, just use
121   // GetValueAtEndOfBlock to do our work.
122   if (!getAvailableVals(AV).count(BB))
123     return GetValueAtEndOfBlock(BB);
124
125   if (BB->pred_empty())
126     llvm_unreachable("Unreachable block!");
127
128   // Otherwise, we have the hard case.  Get the live-in values for each
129   // predecessor.
130   SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
131   unsigned SingularValue = 0;
132
133   bool isFirstPred = true;
134   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
135          E = BB->pred_end(); PI != E; ++PI) {
136     MachineBasicBlock *PredBB = *PI;
137     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
138     PredValues.push_back(std::make_pair(PredBB, PredVal));
139
140     // Compute SingularValue.
141     if (isFirstPred) {
142       SingularValue = PredVal;
143       isFirstPred = false;
144     } else if (PredVal != SingularValue)
145       SingularValue = 0;
146   }
147
148   // Otherwise, if all the merged values are the same, just use it.
149   if (SingularValue != 0)
150     return SingularValue;
151
152   // Otherwise, we do need a PHI: insert one now.
153   MachineInstr *InsertedPHI = InsertNewPHI(BB, VRC, MRI, TII);
154
155   // Fill in all the predecessors of the PHI.
156   MachineInstrBuilder MIB(InsertedPHI);
157   for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
158     MIB.addReg(PredValues[i].second).addMBB(PredValues[i].first);
159
160   // See if the PHI node can be merged to a single value.  This can happen in
161   // loop cases when we get a PHI of itself and one other value.
162   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
163     InsertedPHI->eraseFromParent();
164     return ConstVal;
165   }
166
167   // If the client wants to know about all new instructions, tell it.
168   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
169
170   DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
171   return InsertedPHI->getOperand(0).getReg();
172 }
173
174 static
175 MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
176                                          MachineOperand *U) {
177   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
178     if (&MI->getOperand(i) == U)
179       return MI->getOperand(i+1).getMBB();
180   }
181
182   llvm_unreachable("MachineOperand::getParent() failure?");
183   return 0;
184 }
185
186 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
187 /// which use their value in the corresponding predecessor.
188 void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
189   MachineInstr *UseMI = U.getParent();
190   unsigned NewVR = 0;
191   if (UseMI->getOpcode() == TargetInstrInfo::PHI) {
192     MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
193     NewVR = GetValueAtEndOfBlock(SourceBB);
194   } else {
195     NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
196   }
197
198   U.setReg(NewVR);
199 }
200
201 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
202 /// for the specified BB and if so, return it.  If not, construct SSA form by
203 /// walking predecessors inserting PHI nodes as needed until we get to a block
204 /// where the value is available.
205 ///
206 unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
207   AvailableValsTy &AvailableVals = getAvailableVals(AV);
208
209   // Query AvailableVals by doing an insertion of null.
210   std::pair<AvailableValsTy::iterator, bool> InsertRes =
211     AvailableVals.insert(std::make_pair(BB, 0));
212
213   // Handle the case when the insertion fails because we have already seen BB.
214   if (!InsertRes.second) {
215     // If the insertion failed, there are two cases.  The first case is that the
216     // value is already available for the specified block.  If we get this, just
217     // return the value.
218     if (InsertRes.first->second != 0)
219       return InsertRes.first->second;
220
221     // Otherwise, if the value we find is null, then this is the value is not
222     // known but it is being computed elsewhere in our recursion.  This means
223     // that we have a cycle.  Handle this by inserting a PHI node and returning
224     // it.  When we get back to the first instance of the recursion we will fill
225     // in the PHI node.
226     MachineInstr *NewPHI = InsertNewPHI(BB, VRC, MRI, TII);
227     unsigned NewVR = NewPHI->getOperand(0).getReg();
228     InsertRes.first->second = NewVR;
229     return NewVR;
230   }
231
232   if (BB->pred_empty())
233     llvm_unreachable("Unreachable block!");
234
235   // Okay, the value isn't in the map and we just inserted a null in the entry
236   // to indicate that we're processing the block.  Since we have no idea what
237   // value is in this block, we have to recurse through our predecessors.
238   //
239   // While we're walking our predecessors, we keep track of them in a vector,
240   // then insert a PHI node in the end if we actually need one.  We could use a
241   // smallvector here, but that would take a lot of stack space for every level
242   // of the recursion, just use IncomingPredInfo as an explicit stack.
243   IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
244   unsigned FirstPredInfoEntry = IncomingPredInfo.size();
245
246   // As we're walking the predecessors, keep track of whether they are all
247   // producing the same value.  If so, this value will capture it, if not, it
248   // will get reset to null.  We distinguish the no-predecessor case explicitly
249   // below.
250   unsigned SingularValue = 0;
251   bool isFirstPred = true;
252   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
253          E = BB->pred_end(); PI != E; ++PI) {
254     MachineBasicBlock *PredBB = *PI;
255     unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
256     IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
257
258     // Compute SingularValue.
259     if (isFirstPred) {
260       SingularValue = PredVal;
261       isFirstPred = false;
262     } else if (PredVal != SingularValue)
263       SingularValue = 0;
264   }
265
266   /// Look up BB's entry in AvailableVals.  'InsertRes' may be invalidated.  If
267   /// this block is involved in a loop, a no-entry PHI node will have been
268   /// inserted as InsertedVal.  Otherwise, we'll still have the null we inserted
269   /// above.
270   unsigned InsertedVal = AvailableVals[BB];
271
272   // If all the predecessor values are the same then we don't need to insert a
273   // PHI.  This is the simple and common case.
274   if (SingularValue) {
275     // If a PHI node got inserted, replace it with the singlar value and delete
276     // it.
277     if (InsertedVal) {
278       MachineInstr *OldVal = MRI->getVRegDef(InsertedVal);
279       // Be careful about dead loops.  These RAUW's also update InsertedVal.
280       assert(InsertedVal != SingularValue && "Dead loop?");
281       MRI->replaceRegWith(InsertedVal, SingularValue);
282       OldVal->eraseFromParent();
283     } else {
284       InsertedVal = SingularValue;
285     }
286
287     // Drop the entries we added in IncomingPredInfo to restore the stack.
288     IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
289                            IncomingPredInfo.end());
290     return InsertedVal;
291   }
292
293
294   // Otherwise, we do need a PHI: insert one now if we don't already have one.
295   MachineInstr *InsertedPHI;
296   if (InsertedVal == 0) {
297     InsertedPHI = InsertNewPHI(BB, VRC, MRI, TII);
298     InsertedVal = InsertedPHI->getOperand(0).getReg();
299   } else {
300     InsertedPHI = MRI->getVRegDef(InsertedVal);
301   }
302
303   // Fill in all the predecessors of the PHI.
304   MachineInstrBuilder MIB(InsertedPHI);
305   for (IncomingPredInfoTy::iterator I =
306          IncomingPredInfo.begin()+FirstPredInfoEntry,
307          E = IncomingPredInfo.end(); I != E; ++I)
308     MIB.addReg(I->second).addMBB(I->first);
309
310   // Drop the entries we added in IncomingPredInfo to restore the stack.
311   IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
312                          IncomingPredInfo.end());
313
314   // See if the PHI node can be merged to a single value.  This can happen in
315   // loop cases when we get a PHI of itself and one other value.
316   if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
317     MRI->replaceRegWith(InsertedVal, ConstVal);
318     InsertedPHI->eraseFromParent();
319     InsertedVal = ConstVal;
320   } else {
321     DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
322
323     // If the client wants to know about all new instructions, tell it.
324     if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
325   }
326
327   return InsertedVal;
328
329 }