1 //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PHITransAddr class.
12 //===----------------------------------------------------------------------===//
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"
20 static bool CanPHITrans(Instruction *Inst) {
21 if (isa<PHINode>(Inst) ||
22 isa<BitCastInst>(Inst) ||
23 isa<GetElementPtrInst>(Inst))
26 if (Inst->getOpcode() == Instruction::Add &&
27 isa<ConstantInt>(Inst->getOperand(1)))
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);
36 void PHITransAddr::dump() const {
38 errs() << "PHITransAddr: null\n";
41 errs() << "PHITransAddr: " << *Addr << "\n";
42 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
43 errs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
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;
53 // If it's an instruction, it is either in Tmp or its operands recursively
55 SmallVectorImpl<Instruction*>::iterator Entry =
56 std::find(InstInputs.begin(), InstInputs.end(), I);
57 if (Entry != InstInputs.end()) {
58 InstInputs.erase(Entry);
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";
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))
79 /// Verify - Check internal consistency of this data structure. If the
80 /// structure is valid, it returns true. If invalid, it prints errors and
82 bool PHITransAddr::Verify() const {
83 if (Addr == 0) return true;
85 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
87 if (!VerifySubExpr(Addr, Tmp))
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";
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);
113 static void RemoveInstInputs(Value *V,
114 SmallVectorImpl<Instruction*> &InstInputs) {
115 Instruction *I = dyn_cast<Instruction>(V);
118 // If the instruction is in the InstInputs list, remove it.
119 SmallVectorImpl<Instruction*>::iterator Entry =
120 std::find(InstInputs.begin(), InstInputs.end(), I);
121 if (Entry != InstInputs.end()) {
122 InstInputs.erase(Entry);
126 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
128 // Otherwise, it must have instruction inputs itself. Zap them recursively.
129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
130 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
131 RemoveInstInputs(Op, InstInputs);
135 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
136 BasicBlock *PredBB) {
137 // If this is a non-instruction value, it can't require PHI translation.
138 Instruction *Inst = dyn_cast<Instruction>(V);
139 if (Inst == 0) return V;
141 // Determine whether 'Inst' is an input to our PHI translatable expression.
142 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
144 // Handle inputs instructions if needed.
146 if (Inst->getParent() != CurBB) {
147 // If it is an input defined in a different block, then it remains an
152 // If 'Inst' is defined in this block and is an input that needs to be phi
153 // translated, we need to incorporate the value into the expression or fail.
155 // In either case, the instruction itself isn't an input any longer.
156 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
158 // If this is a PHI, go ahead and translate it.
159 if (PHINode *PN = dyn_cast<PHINode>(Inst))
160 return AddAsInput(PN->getIncomingValueForBlock(PredBB));
162 // If this is a non-phi value, and it is analyzable, we can incorporate it
163 // into the expression by making all instruction operands be inputs.
164 if (!CanPHITrans(Inst))
167 // All instruction operands are now inputs (and of course, they may also be
168 // defined in this block, so they may need to be phi translated themselves.
169 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
170 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
171 InstInputs.push_back(Op);
174 // Ok, it must be an intermediate result (either because it started that way
175 // or because we just incorporated it into the expression). See if its
176 // operands need to be phi translated, and if so, reconstruct it.
178 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
179 Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB);
180 if (PHIIn == 0) return 0;
181 if (PHIIn == BC->getOperand(0))
184 // Find an available version of this cast.
186 // Constants are trivial to find.
187 if (Constant *C = dyn_cast<Constant>(PHIIn))
188 return AddAsInput(ConstantExpr::getBitCast(C, BC->getType()));
190 // Otherwise we have to see if a bitcasted version of the incoming pointer
191 // is available. If so, we can use it, otherwise we have to fail.
192 for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
194 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI))
195 if (BCI->getType() == BC->getType())
201 // Handle getelementptr with at least one PHI translatable operand.
202 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
203 SmallVector<Value*, 8> GEPOps;
204 bool AnyChanged = false;
205 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
206 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB);
207 if (GEPOp == 0) return 0;
209 AnyChanged |= GEPOp != GEP->getOperand(i);
210 GEPOps.push_back(GEPOp);
216 // Simplify the GEP to handle 'gep x, 0' -> x etc.
217 if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD)) {
218 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
219 RemoveInstInputs(GEPOps[i], InstInputs);
221 return AddAsInput(V);
224 // Scan to see if we have this GEP available.
225 Value *APHIOp = GEPOps[0];
226 for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
229 if (GEPI->getType() == GEP->getType() &&
230 GEPI->getNumOperands() == GEPOps.size() &&
231 GEPI->getParent()->getParent() == CurBB->getParent()) {
232 bool Mismatch = false;
233 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
234 if (GEPI->getOperand(i) != GEPOps[i]) {
245 // Handle add with a constant RHS.
246 if (Inst->getOpcode() == Instruction::Add &&
247 isa<ConstantInt>(Inst->getOperand(1))) {
248 // PHI translate the LHS.
249 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
250 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
251 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
253 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB);
254 if (LHS == 0) return 0;
256 // If the PHI translated LHS is an add of a constant, fold the immediates.
257 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
258 if (BOp->getOpcode() == Instruction::Add)
259 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
260 LHS = BOp->getOperand(0);
261 RHS = ConstantExpr::getAdd(RHS, CI);
262 isNSW = isNUW = false;
264 // If the old 'LHS' was an input, add the new 'LHS' as an input.
265 if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
266 RemoveInstInputs(BOp, InstInputs);
271 // See if the add simplifies away.
272 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD)) {
273 // If we simplified the operands, the LHS is no longer an input, but Res
275 RemoveInstInputs(LHS, InstInputs);
276 return AddAsInput(Res);
279 // Otherwise, see if we have this add available somewhere.
280 for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
283 if (BO->getOpcode() == Instruction::Add &&
284 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
285 BO->getParent()->getParent() == CurBB->getParent())
292 // Otherwise, we failed.
297 /// PHITranslateValue - PHI translate the current address up the CFG from
298 /// CurBB to Pred, updating our state the reflect any needed changes. This
299 /// returns true on failure and sets Addr to null.
300 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) {
301 assert(Verify() && "Invalid PHITransAddr!");
302 Addr = PHITranslateSubExpr(Addr, CurBB, PredBB);
303 assert(Verify() && "Invalid PHITransAddr!");
307 /// GetAvailablePHITranslatedSubExpr - Return the value computed by
308 /// PHITranslateSubExpr if it dominates PredBB, otherwise return null.
309 Value *PHITransAddr::
310 GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB,
311 const DominatorTree &DT) const {
312 PHITransAddr Tmp(V, TD);
313 Tmp.PHITranslateValue(CurBB, PredBB);
315 // See if PHI translation succeeds.
318 // Make sure the value is live in the predecessor.
319 if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
320 if (!DT.dominates(Inst->getParent(), PredBB))
326 /// PHITranslateWithInsertion - PHI translate this value into the specified
327 /// predecessor block, inserting a computation of the value if it is
330 /// All newly created instructions are added to the NewInsts list. This
331 /// returns null on failure.
333 Value *PHITransAddr::
334 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
335 const DominatorTree &DT,
336 SmallVectorImpl<Instruction*> &NewInsts) {
337 unsigned NISize = NewInsts.size();
339 // Attempt to PHI translate with insertion.
340 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
342 // If successful, return the new value.
343 if (Addr) return Addr;
345 // If not, destroy any intermediate instructions inserted.
346 while (NewInsts.size() != NISize)
347 NewInsts.pop_back_val()->eraseFromParent();
352 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
353 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
354 /// block. All newly created instructions are added to the NewInsts list.
355 /// This returns null on failure.
357 Value *PHITransAddr::
358 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
359 BasicBlock *PredBB, const DominatorTree &DT,
360 SmallVectorImpl<Instruction*> &NewInsts) {
361 // See if we have a version of this value already available and dominating
362 // PredBB. If so, there is no need to insert a new instance of it.
363 if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT))
366 // If we don't have an available version of this value, it must be an
368 Instruction *Inst = cast<Instruction>(InVal);
370 // Handle bitcast of PHI translatable value.
371 if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {
372 Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0),
373 CurBB, PredBB, DT, NewInsts);
374 if (OpVal == 0) return 0;
376 // Otherwise insert a bitcast at the end of PredBB.
377 BitCastInst *New = new BitCastInst(OpVal, InVal->getType(),
378 InVal->getName()+".phi.trans.insert",
379 PredBB->getTerminator());
380 NewInsts.push_back(New);
384 // Handle getelementptr with at least one PHI operand.
385 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
386 SmallVector<Value*, 8> GEPOps;
387 BasicBlock *CurBB = GEP->getParent();
388 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
389 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
390 CurBB, PredBB, DT, NewInsts);
391 if (OpVal == 0) return 0;
392 GEPOps.push_back(OpVal);
395 GetElementPtrInst *Result =
396 GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
397 InVal->getName()+".phi.trans.insert",
398 PredBB->getTerminator());
399 Result->setIsInBounds(GEP->isInBounds());
400 NewInsts.push_back(Result);
405 // FIXME: This code works, but it is unclear that we actually want to insert
406 // a big chain of computation in order to make a value available in a block.
407 // This needs to be evaluated carefully to consider its cost trade offs.
409 // Handle add with a constant RHS.
410 if (Inst->getOpcode() == Instruction::Add &&
411 isa<ConstantInt>(Inst->getOperand(1))) {
412 // PHI translate the LHS.
413 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
414 CurBB, PredBB, DT, NewInsts);
415 if (OpVal == 0) return 0;
417 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
418 InVal->getName()+".phi.trans.insert",
419 PredBB->getTerminator());
420 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
421 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
422 NewInsts.push_back(Res);