fix PHI translation to take the PHI out of the instinputs set and add
[oota-llvm.git] / lib / Analysis / PHITransAddr.cpp
1 //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
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 PHITransAddr class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/PHITransAddr.h"
15 #include "llvm/Analysis/Dominators.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/raw_ostream.h"
18 using namespace llvm;
19
20 static bool CanPHITrans(Instruction *Inst) {
21   if (isa<PHINode>(Inst) ||
22       isa<BitCastInst>(Inst) ||
23       isa<GetElementPtrInst>(Inst))
24     return true;
25   
26   if (Inst->getOpcode() == Instruction::Add &&
27       isa<ConstantInt>(Inst->getOperand(1)))
28     return true;
29   
30   //   cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
31   //   if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
32   //     cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
33   return false;
34 }
35
36 void PHITransAddr::dump() const {
37   if (Addr == 0) {
38     errs() << "PHITransAddr: null\n";
39     return;
40   }
41   errs() << "PHITransAddr: " << *Addr << "\n";
42   for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
43     errs() << "  Input #" << i << " is " << *InstInputs[i] << "\n";
44 }
45
46
47 static bool VerifySubExpr(Value *Expr,
48                           SmallVectorImpl<Instruction*> &InstInputs) {
49   // If this is a non-instruction value, there is nothing to do.
50   Instruction *I = dyn_cast<Instruction>(Expr);
51   if (I == 0) return true;
52   
53   // If it's an instruction, it is either in Tmp or its operands recursively
54   // are.
55   SmallVectorImpl<Instruction*>::iterator Entry =
56     std::find(InstInputs.begin(), InstInputs.end(), I);
57   if (Entry != InstInputs.end()) {
58     InstInputs.erase(Entry);
59     return true;
60   }
61   
62   // If it isn't in the InstInputs list it is a subexpr incorporated into the
63   // address.  Sanity check that it is phi translatable.
64   if (!CanPHITrans(I)) {
65     errs() << "Non phi translatable instruction found in PHITransAddr, either "
66               "something is missing from InstInputs or CanPHITrans is wrong:\n";
67     errs() << *I << '\n';
68     return false;
69   }
70   
71   // Validate the operands of the instruction.
72   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
73     if (!VerifySubExpr(I->getOperand(i), InstInputs))
74       return false;
75
76   return true;
77 }
78
79 /// Verify - Check internal consistency of this data structure.  If the
80 /// structure is valid, it returns true.  If invalid, it prints errors and
81 /// returns false.
82 bool PHITransAddr::Verify() const {
83   if (Addr == 0) return true;
84   
85   SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());  
86   
87   if (!VerifySubExpr(Addr, Tmp))
88     return false;
89   
90   if (!Tmp.empty()) {
91     errs() << "PHITransAddr inconsistent, contains extra instructions:\n";
92     for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
93       errs() << "  InstInput #" << i << " is " << *InstInputs[i] << "\n";
94     return false;
95   }
96   
97   // a-ok.
98   return true;
99 }
100
101
102 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
103 /// if we have some hope of doing it.  This should be used as a filter to
104 /// avoid calling PHITranslateValue in hopeless situations.
105 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
106   // If the input value is not an instruction, or if it is not defined in CurBB,
107   // then we don't need to phi translate it.
108   Instruction *Inst = dyn_cast<Instruction>(Addr);
109   return Inst == 0 || CanPHITrans(Inst);
110 }
111
112
113 static void RemoveInstInputs(Instruction *I, 
114                              SmallVectorImpl<Instruction*> &InstInputs) {
115   // If the instruction is in the InstInputs list, remove it.
116   SmallVectorImpl<Instruction*>::iterator Entry =
117     std::find(InstInputs.begin(), InstInputs.end(), I);
118   if (Entry != InstInputs.end()) {
119     InstInputs.erase(Entry);
120     return;
121   }
122   
123   // Otherwise, it must have instruction inputs itself.  Zap them recursively.
124   bool HadInstInputs = false;
125   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
126     if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i))) {
127       RemoveInstInputs(Op, InstInputs);
128       HadInstInputs = true;
129     }
130   }
131
132   // This instruction had to have operands in the instinputs list or it should
133   // have been in the list itself.  If not, the list is broken.
134   assert(HadInstInputs && "InstInputs list inconsistent!");
135 }
136
137 /// ReplaceInstWithValue - Remove any instruction inputs in the InstInputs
138 /// array that are due to the specified instruction that is about to be
139 /// removed from the address, and add any corresponding to V.  This returns V.
140 Value *PHITransAddr::ReplaceInstWithValue(Instruction *I, Value *V) {
141   // Remove the old instruction from InstInputs.
142   RemoveInstInputs(I, InstInputs);
143   
144   // If V is an instruction, it is now an input.
145   if (Instruction *VI = dyn_cast<Instruction>(V))
146     InstInputs.push_back(VI);
147   return V;
148 }
149
150
151 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
152                                          BasicBlock *PredBB) {
153   // If this is a non-instruction value, it can't require PHI translation.
154   Instruction *Inst = dyn_cast<Instruction>(V);
155   if (Inst == 0) return V;
156   
157   // Determine whether 'Inst' is an input to our PHI translatable expression.
158   bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
159
160   // Handle inputs instructions if needed.
161   if (isInput) {
162     if (Inst->getParent() != CurBB) {
163       // If it is an input defined in a different block, then it remains an
164       // input.
165       return Inst;
166     }
167
168     // If 'Inst' is defined in this block and is an input that needs to be phi
169     // translated, we need to incorporate the value into the expression or fail.
170
171     // If this is a PHI, go ahead and translate it.
172     if (PHINode *PN = dyn_cast<PHINode>(Inst))
173       return ReplaceInstWithValue(PN, PN->getIncomingValueForBlock(PredBB));
174     
175     // If this is a non-phi value, and it is analyzable, we can incorporate it
176     // into the expression by making all instruction operands be inputs.
177     if (!CanPHITrans(Inst))
178       return 0;
179    
180     // The instruction itself isn't an input any longer.
181     InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
182     
183     // All instruction operands are now inputs (and of course, they may also be
184     // defined in this block, so they may need to be phi translated themselves.
185     for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
186       if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
187         InstInputs.push_back(Op);
188   }
189
190   // Ok, it must be an intermediate result (either because it started that way
191   // or because we just incorporated it into the expression).  See if its
192   // operands need to be phi translated, and if so, reconstruct it.
193   
194   if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
195     Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB);
196     if (PHIIn == 0) return 0;
197     if (PHIIn == BC->getOperand(0))
198       return BC;
199     
200     // Find an available version of this cast.
201     
202     // Constants are trivial to find.
203     if (Constant *C = dyn_cast<Constant>(PHIIn))
204       return ReplaceInstWithValue(BC, ConstantExpr::getBitCast(C,
205                                                                BC->getType()));
206     
207     // Otherwise we have to see if a bitcasted version of the incoming pointer
208     // is available.  If so, we can use it, otherwise we have to fail.
209     for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
210          UI != E; ++UI) {
211       if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI))
212         if (BCI->getType() == BC->getType())
213           return BCI;
214     }
215     return 0;
216   }
217   
218   // Handle getelementptr with at least one PHI translatable operand.
219   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
220     SmallVector<Value*, 8> GEPOps;
221     BasicBlock *CurBB = GEP->getParent();
222     bool AnyChanged = false;
223     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
224       Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB);
225       if (GEPOp == 0) return 0;
226       
227       AnyChanged |= GEPOp != GEP->getOperand(i);
228       GEPOps.push_back(GEPOp);
229     }
230     
231     if (!AnyChanged)
232       return GEP;
233     
234     // Simplify the GEP to handle 'gep x, 0' -> x etc.
235     if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD))
236       return ReplaceInstWithValue(GEP, V);
237     
238     // Scan to see if we have this GEP available.
239     Value *APHIOp = GEPOps[0];
240     for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
241          UI != E; ++UI) {
242       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
243         if (GEPI->getType() == GEP->getType() &&
244             GEPI->getNumOperands() == GEPOps.size() &&
245             GEPI->getParent()->getParent() == CurBB->getParent()) {
246           bool Mismatch = false;
247           for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
248             if (GEPI->getOperand(i) != GEPOps[i]) {
249               Mismatch = true;
250               break;
251             }
252           if (!Mismatch)
253             return GEPI;
254         }
255     }
256     return 0;
257   }
258   
259   // Handle add with a constant RHS.
260   if (Inst->getOpcode() == Instruction::Add &&
261       isa<ConstantInt>(Inst->getOperand(1))) {
262     // PHI translate the LHS.
263     Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
264     bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
265     bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
266     
267     Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB);
268     if (LHS == 0) return 0;
269     
270     // If the PHI translated LHS is an add of a constant, fold the immediates.
271     if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
272       if (BOp->getOpcode() == Instruction::Add)
273         if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
274           LHS = BOp->getOperand(0);
275           RHS = ConstantExpr::getAdd(RHS, CI);
276           isNSW = isNUW = false;
277         }
278     
279     // See if the add simplifies away.
280     if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD))
281       return ReplaceInstWithValue(Inst, Res);
282     
283     // Otherwise, see if we have this add available somewhere.
284     for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
285          UI != E; ++UI) {
286       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
287         if (BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
288             BO->getParent()->getParent() == CurBB->getParent())
289           return BO;
290     }
291     
292     return 0;
293   }
294   
295   // Otherwise, we failed.
296   return 0;
297 }
298
299
300 /// PHITranslateValue - PHI translate the current address up the CFG from
301 /// CurBB to Pred, updating our state the reflect any needed changes.  This
302 /// returns true on failure and sets Addr to null.
303 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) {
304   assert(Verify() && "Invalid PHITransAddr!");
305   Addr = PHITranslateSubExpr(Addr, CurBB, PredBB);
306   assert(Verify() && "Invalid PHITransAddr!");
307   return Addr == 0;
308 }
309
310 /// GetAvailablePHITranslatedSubExpr - Return the value computed by
311 /// PHITranslateSubExpr if it dominates PredBB, otherwise return null.
312 Value *PHITransAddr::
313 GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB,
314                                  const DominatorTree &DT) const {
315   PHITransAddr Tmp(V, TD);
316   Tmp.PHITranslateValue(CurBB, PredBB);
317   
318   // See if PHI translation succeeds.
319   V = Tmp.getAddr();
320   
321   // Make sure the value is live in the predecessor.
322   if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
323     if (!DT.dominates(Inst->getParent(), PredBB))
324       return 0;
325   return V;
326 }
327
328
329 /// PHITranslateWithInsertion - PHI translate this value into the specified
330 /// predecessor block, inserting a computation of the value if it is
331 /// unavailable.
332 ///
333 /// All newly created instructions are added to the NewInsts list.  This
334 /// returns null on failure.
335 ///
336 Value *PHITransAddr::
337 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
338                           const DominatorTree &DT,
339                           SmallVectorImpl<Instruction*> &NewInsts) {
340   unsigned NISize = NewInsts.size();
341   
342   // Attempt to PHI translate with insertion.
343   Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
344   
345   // If successful, return the new value.
346   if (Addr) return Addr;
347   
348   // If not, destroy any intermediate instructions inserted.
349   while (NewInsts.size() != NISize)
350     NewInsts.pop_back_val()->eraseFromParent();
351   return 0;
352 }
353
354
355 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
356 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
357 /// block.  All newly created instructions are added to the NewInsts list.
358 /// This returns null on failure.
359 ///
360 Value *PHITransAddr::
361 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
362                            BasicBlock *PredBB, const DominatorTree &DT,
363                            SmallVectorImpl<Instruction*> &NewInsts) {
364   // See if we have a version of this value already available and dominating
365   // PredBB.  If so, there is no need to insert a new instance of it.
366   if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT))
367     return Res;
368
369   // If we don't have an available version of this value, it must be an
370   // instruction.
371   Instruction *Inst = cast<Instruction>(InVal);
372   
373   // Handle bitcast of PHI translatable value.
374   if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
375     Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0),
376                                               CurBB, PredBB, DT, NewInsts);
377     if (OpVal == 0) return 0;
378     
379     // Otherwise insert a bitcast at the end of PredBB.
380     BitCastInst *New = new BitCastInst(OpVal, InVal->getType(),
381                                        InVal->getName()+".phi.trans.insert",
382                                        PredBB->getTerminator());
383     NewInsts.push_back(New);
384     return New;
385   }
386   
387   // Handle getelementptr with at least one PHI operand.
388   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
389     SmallVector<Value*, 8> GEPOps;
390     BasicBlock *CurBB = GEP->getParent();
391     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
392       Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
393                                                 CurBB, PredBB, DT, NewInsts);
394       if (OpVal == 0) return 0;
395       GEPOps.push_back(OpVal);
396     }
397     
398     GetElementPtrInst *Result = 
399     GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
400                               InVal->getName()+".phi.trans.insert",
401                               PredBB->getTerminator());
402     Result->setIsInBounds(GEP->isInBounds());
403     NewInsts.push_back(Result);
404     return Result;
405   }
406   
407 #if 0
408   // FIXME: This code works, but it is unclear that we actually want to insert
409   // a big chain of computation in order to make a value available in a block.
410   // This needs to be evaluated carefully to consider its cost trade offs.
411   
412   // Handle add with a constant RHS.
413   if (Inst->getOpcode() == Instruction::Add &&
414       isa<ConstantInt>(Inst->getOperand(1))) {
415     // PHI translate the LHS.
416     Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
417                                               CurBB, PredBB, DT, NewInsts);
418     if (OpVal == 0) return 0;
419     
420     BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
421                                            InVal->getName()+".phi.trans.insert",
422                                                     PredBB->getTerminator());
423     Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
424     Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
425     NewInsts.push_back(Res);
426     return Res;
427   }
428 #endif
429   
430   return 0;
431 }