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