OSDN Git Service

fix a typo (and -> add) and fix GetAvailablePHITranslatedSubExpr to not
[android-x86/external-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 using namespace llvm;
18
19 static bool CanPHITrans(Instruction *Inst) {
20   if (isa<PHINode>(Inst) ||
21       isa<BitCastInst>(Inst) ||
22       isa<GetElementPtrInst>(Inst))
23     return true;
24   
25   if (Inst->getOpcode() == Instruction::Add &&
26       isa<ConstantInt>(Inst->getOperand(1)))
27     return true;
28   
29   //   cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
30   //   if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
31   //     cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
32   return false;
33 }
34
35 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
36 /// if we have some hope of doing it.  This should be used as a filter to
37 /// avoid calling PHITranslateValue in hopeless situations.
38 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
39   // If the input value is not an instruction, or if it is not defined in CurBB,
40   // then we don't need to phi translate it.
41   Instruction *Inst = dyn_cast<Instruction>(Addr);
42   return Inst == 0 || CanPHITrans(Inst);
43 }
44
45
46 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
47                                          BasicBlock *PredBB) {
48   // If this is a non-instruction value, it can't require PHI translation.
49   Instruction *Inst = dyn_cast<Instruction>(V);
50   if (Inst == 0) return V;
51   
52   // If 'Inst' is defined in this block, it must be an input that needs to be
53   // phi translated or an intermediate expression that needs to be incorporated
54   // into the expression.
55   if (Inst->getParent() == CurBB) {
56     assert(std::count(InstInputs.begin(), InstInputs.end(), Inst) &&
57            "Not an input?");
58     
59     // If this is a PHI, go ahead and translate it.
60     if (PHINode *PN = dyn_cast<PHINode>(Inst))
61       return PN->getIncomingValueForBlock(PredBB);
62
63     
64     // If this is a non-phi value, and it is analyzable, we can incorporate it
65     // into the expression by making all instruction operands be inputs.
66     if (!CanPHITrans(Inst))
67       return 0;
68     
69     // Okay, we can incorporate it, this instruction is no longer an input.
70     InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
71     
72     // All instruction operands are now inputs (and of course, they may also be
73     // defined in this block, so they may need to be phi translated themselves.
74     for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
75       if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
76         InstInputs.push_back(Op);
77     
78   } else {
79     // Determine whether 'Inst' is an input to our PHI translatable expression.
80     bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
81     
82     // If it is an input defined in a different block, then it remains an input.
83     if (isInput)
84       return Inst;
85   }
86
87   // Ok, it must be an intermediate result (either because it started that way
88   // or because we just incorporated it into the expression).  See if its
89   // operands need to be phi translated, and if so, reconstruct it.
90   
91   if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
92     Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB);
93     if (PHIIn == 0) return 0;
94     if (PHIIn == BC->getOperand(0))
95       return BC;
96     
97     // Find an available version of this cast.
98     
99     // Constants are trivial to find.
100     if (Constant *C = dyn_cast<Constant>(PHIIn))
101       return ConstantExpr::getBitCast(C, BC->getType());
102     
103     // Otherwise we have to see if a bitcasted version of the incoming pointer
104     // is available.  If so, we can use it, otherwise we have to fail.
105     for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
106          UI != E; ++UI) {
107       if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI))
108         if (BCI->getType() == BC->getType())
109           return BCI;
110     }
111     return 0;
112   }
113   
114   // Handle getelementptr with at least one PHI translatable operand.
115   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
116     SmallVector<Value*, 8> GEPOps;
117     BasicBlock *CurBB = GEP->getParent();
118     bool AnyChanged = false;
119     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
120       Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB);
121       if (GEPOp == 0) return 0;
122       
123       AnyChanged |= GEPOp != GEP->getOperand(i);
124       GEPOps.push_back(GEPOp);
125     }
126     
127     if (!AnyChanged)
128       return GEP;
129     
130     // Simplify the GEP to handle 'gep x, 0' -> x etc.
131     if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD))
132       return V;
133     
134     // Scan to see if we have this GEP available.
135     Value *APHIOp = GEPOps[0];
136     for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
137          UI != E; ++UI) {
138       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
139         if (GEPI->getType() == GEP->getType() &&
140             GEPI->getNumOperands() == GEPOps.size() &&
141             GEPI->getParent()->getParent() == CurBB->getParent()) {
142           bool Mismatch = false;
143           for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
144             if (GEPI->getOperand(i) != GEPOps[i]) {
145               Mismatch = true;
146               break;
147             }
148           if (!Mismatch)
149             return GEPI;
150         }
151     }
152     return 0;
153   }
154   
155   // Handle add with a constant RHS.
156   if (Inst->getOpcode() == Instruction::Add &&
157       isa<ConstantInt>(Inst->getOperand(1))) {
158     // PHI translate the LHS.
159     Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
160     bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
161     bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
162     
163     Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB);
164     if (LHS == 0) return 0;
165     
166     // If the PHI translated LHS is an add of a constant, fold the immediates.
167     if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
168       if (BOp->getOpcode() == Instruction::Add)
169         if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
170           LHS = BOp->getOperand(0);
171           RHS = ConstantExpr::getAdd(RHS, CI);
172           isNSW = isNUW = false;
173         }
174     
175     // See if the add simplifies away.
176     if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD))
177       return Res;
178     
179     // Otherwise, see if we have this add available somewhere.
180     for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
181          UI != E; ++UI) {
182       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
183         if (BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
184             BO->getParent()->getParent() == CurBB->getParent())
185           return BO;
186     }
187     
188     return 0;
189   }
190   
191   // Otherwise, we failed.
192   return 0;
193 }
194
195
196 /// PHITranslateValue - PHI translate the current address up the CFG from
197 /// CurBB to Pred, updating our state the reflect any needed changes.  This
198 /// returns true on failure and sets Addr to null.
199 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) {
200   Addr = PHITranslateSubExpr(Addr, CurBB, PredBB);
201   return Addr == 0;
202 }
203
204 /// GetAvailablePHITranslatedSubExpr - Return the value computed by
205 /// PHITranslateSubExpr if it dominates PredBB, otherwise return null.
206 Value *PHITransAddr::
207 GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB,
208                                  const DominatorTree &DT) const {
209   PHITransAddr Tmp(V, TD);
210   Tmp.PHITranslateValue(CurBB, PredBB);
211   
212   // See if PHI translation succeeds.
213   V = Tmp.getAddr();
214   
215   // Make sure the value is live in the predecessor.
216   if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
217     if (!DT.dominates(Inst->getParent(), PredBB))
218       return 0;
219   return V;
220 }
221
222
223 /// PHITranslateWithInsertion - PHI translate this value into the specified
224 /// predecessor block, inserting a computation of the value if it is
225 /// unavailable.
226 ///
227 /// All newly created instructions are added to the NewInsts list.  This
228 /// returns null on failure.
229 ///
230 Value *PHITransAddr::
231 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
232                           const DominatorTree &DT,
233                           SmallVectorImpl<Instruction*> &NewInsts) {
234   unsigned NISize = NewInsts.size();
235   
236   // Attempt to PHI translate with insertion.
237   Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
238   
239   // If successful, return the new value.
240   if (Addr) return Addr;
241   
242   // If not, destroy any intermediate instructions inserted.
243   while (NewInsts.size() != NISize)
244     NewInsts.pop_back_val()->eraseFromParent();
245   return 0;
246 }
247
248
249 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
250 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
251 /// block.  All newly created instructions are added to the NewInsts list.
252 /// This returns null on failure.
253 ///
254 Value *PHITransAddr::
255 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
256                            BasicBlock *PredBB, const DominatorTree &DT,
257                            SmallVectorImpl<Instruction*> &NewInsts) {
258   // See if we have a version of this value already available and dominating
259   // PredBB.  If so, there is no need to insert a new instance of it.
260   if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT))
261     return Res;
262
263   // If we don't have an available version of this value, it must be an
264   // instruction.
265   Instruction *Inst = cast<Instruction>(InVal);
266   
267   // Handle bitcast of PHI translatable value.
268   if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
269     Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0),
270                                               CurBB, PredBB, DT, NewInsts);
271     if (OpVal == 0) return 0;
272     
273     // Otherwise insert a bitcast at the end of PredBB.
274     BitCastInst *New = new BitCastInst(OpVal, InVal->getType(),
275                                        InVal->getName()+".phi.trans.insert",
276                                        PredBB->getTerminator());
277     NewInsts.push_back(New);
278     return New;
279   }
280   
281   // Handle getelementptr with at least one PHI operand.
282   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
283     SmallVector<Value*, 8> GEPOps;
284     BasicBlock *CurBB = GEP->getParent();
285     for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
286       Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
287                                                 CurBB, PredBB, DT, NewInsts);
288       if (OpVal == 0) return 0;
289       GEPOps.push_back(OpVal);
290     }
291     
292     GetElementPtrInst *Result = 
293     GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
294                               InVal->getName()+".phi.trans.insert",
295                               PredBB->getTerminator());
296     Result->setIsInBounds(GEP->isInBounds());
297     NewInsts.push_back(Result);
298     return Result;
299   }
300   
301 #if 0
302   // FIXME: This code works, but it is unclear that we actually want to insert
303   // a big chain of computation in order to make a value available in a block.
304   // This needs to be evaluated carefully to consider its cost trade offs.
305   
306   // Handle add with a constant RHS.
307   if (Inst->getOpcode() == Instruction::Add &&
308       isa<ConstantInt>(Inst->getOperand(1))) {
309     // PHI translate the LHS.
310     Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
311                                               CurBB, PredBB, DT, NewInsts);
312     if (OpVal == 0) return 0;
313     
314     BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
315                                            InVal->getName()+".phi.trans.insert",
316                                                     PredBB->getTerminator());
317     Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
318     Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
319     NewInsts.push_back(Res);
320     return Res;
321   }
322 #endif
323   
324   return 0;
325 }