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