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