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/Instructions.h"
16 #include "llvm/Analysis/Dominators.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
23 static bool CanPHITrans(Instruction *Inst) {
24 if (isa<PHINode>(Inst) ||
25 isa<GetElementPtrInst>(Inst))
28 if (isa<CastInst>(Inst) &&
29 Inst->isSafeToSpeculativelyExecute())
32 if (Inst->getOpcode() == Instruction::Add &&
33 isa<ConstantInt>(Inst->getOperand(1)))
36 // cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
37 // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
38 // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
42 void PHITransAddr::dump() const {
44 dbgs() << "PHITransAddr: null\n";
47 dbgs() << "PHITransAddr: " << *Addr << "\n";
48 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
49 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
53 static bool VerifySubExpr(Value *Expr,
54 SmallVectorImpl<Instruction*> &InstInputs) {
55 // If this is a non-instruction value, there is nothing to do.
56 Instruction *I = dyn_cast<Instruction>(Expr);
57 if (I == 0) return true;
59 // If it's an instruction, it is either in Tmp or its operands recursively
61 SmallVectorImpl<Instruction*>::iterator Entry =
62 std::find(InstInputs.begin(), InstInputs.end(), I);
63 if (Entry != InstInputs.end()) {
64 InstInputs.erase(Entry);
68 // If it isn't in the InstInputs list it is a subexpr incorporated into the
69 // address. Sanity check that it is phi translatable.
70 if (!CanPHITrans(I)) {
71 errs() << "Non phi translatable instruction found in PHITransAddr:\n";
73 llvm_unreachable("Either something is missing from InstInputs or "
74 "CanPHITrans is wrong.");
78 // Validate the operands of the instruction.
79 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
80 if (!VerifySubExpr(I->getOperand(i), InstInputs))
86 /// Verify - Check internal consistency of this data structure. If the
87 /// structure is valid, it returns true. If invalid, it prints errors and
89 bool PHITransAddr::Verify() const {
90 if (Addr == 0) return true;
92 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
94 if (!VerifySubExpr(Addr, Tmp))
98 errs() << "PHITransAddr contains extra instructions:\n";
99 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
100 errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
101 llvm_unreachable("This is unexpected.");
110 /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
111 /// if we have some hope of doing it. This should be used as a filter to
112 /// avoid calling PHITranslateValue in hopeless situations.
113 bool PHITransAddr::IsPotentiallyPHITranslatable() const {
114 // If the input value is not an instruction, or if it is not defined in CurBB,
115 // then we don't need to phi translate it.
116 Instruction *Inst = dyn_cast<Instruction>(Addr);
117 return Inst == 0 || CanPHITrans(Inst);
121 static void RemoveInstInputs(Value *V,
122 SmallVectorImpl<Instruction*> &InstInputs) {
123 Instruction *I = dyn_cast<Instruction>(V);
126 // If the instruction is in the InstInputs list, remove it.
127 SmallVectorImpl<Instruction*>::iterator Entry =
128 std::find(InstInputs.begin(), InstInputs.end(), I);
129 if (Entry != InstInputs.end()) {
130 InstInputs.erase(Entry);
134 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
136 // Otherwise, it must have instruction inputs itself. Zap them recursively.
137 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
138 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
139 RemoveInstInputs(Op, InstInputs);
143 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
145 const DominatorTree *DT) {
146 // If this is a non-instruction value, it can't require PHI translation.
147 Instruction *Inst = dyn_cast<Instruction>(V);
148 if (Inst == 0) return V;
150 // Determine whether 'Inst' is an input to our PHI translatable expression.
151 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
153 // Handle inputs instructions if needed.
155 if (Inst->getParent() != CurBB) {
156 // If it is an input defined in a different block, then it remains an
161 // If 'Inst' is defined in this block and is an input that needs to be phi
162 // translated, we need to incorporate the value into the expression or fail.
164 // In either case, the instruction itself isn't an input any longer.
165 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
167 // If this is a PHI, go ahead and translate it.
168 if (PHINode *PN = dyn_cast<PHINode>(Inst))
169 return AddAsInput(PN->getIncomingValueForBlock(PredBB));
171 // If this is a non-phi value, and it is analyzable, we can incorporate it
172 // into the expression by making all instruction operands be inputs.
173 if (!CanPHITrans(Inst))
176 // All instruction operands are now inputs (and of course, they may also be
177 // defined in this block, so they may need to be phi translated themselves.
178 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
179 if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
180 InstInputs.push_back(Op);
183 // Ok, it must be an intermediate result (either because it started that way
184 // or because we just incorporated it into the expression). See if its
185 // operands need to be phi translated, and if so, reconstruct it.
187 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
188 if (!Cast->isSafeToSpeculativelyExecute()) return 0;
189 Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
190 if (PHIIn == 0) return 0;
191 if (PHIIn == Cast->getOperand(0))
194 // Find an available version of this cast.
196 // Constants are trivial to find.
197 if (Constant *C = dyn_cast<Constant>(PHIIn))
198 return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
199 C, Cast->getType()));
201 // Otherwise we have to see if a casted version of the incoming pointer
202 // is available. If so, we can use it, otherwise we have to fail.
203 for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end();
205 if (CastInst *CastI = dyn_cast<CastInst>(*UI))
206 if (CastI->getOpcode() == Cast->getOpcode() &&
207 CastI->getType() == Cast->getType() &&
208 (!DT || DT->dominates(CastI->getParent(), PredBB)))
214 // Handle getelementptr with at least one PHI translatable operand.
215 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
216 SmallVector<Value*, 8> GEPOps;
217 bool AnyChanged = false;
218 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
219 Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
220 if (GEPOp == 0) return 0;
222 AnyChanged |= GEPOp != GEP->getOperand(i);
223 GEPOps.push_back(GEPOp);
229 // Simplify the GEP to handle 'gep x, 0' -> x etc.
230 if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD, DT)) {
231 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
232 RemoveInstInputs(GEPOps[i], InstInputs);
234 return AddAsInput(V);
237 // Scan to see if we have this GEP available.
238 Value *APHIOp = GEPOps[0];
239 for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end();
241 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
242 if (GEPI->getType() == GEP->getType() &&
243 GEPI->getNumOperands() == GEPOps.size() &&
244 GEPI->getParent()->getParent() == CurBB->getParent() &&
245 (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
246 bool Mismatch = false;
247 for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
248 if (GEPI->getOperand(i) != GEPOps[i]) {
259 // Handle add with a constant RHS.
260 if (Inst->getOpcode() == Instruction::Add &&
261 isa<ConstantInt>(Inst->getOperand(1))) {
262 // PHI translate the LHS.
263 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
264 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
265 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
267 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
268 if (LHS == 0) return 0;
270 // If the PHI translated LHS is an add of a constant, fold the immediates.
271 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
272 if (BOp->getOpcode() == Instruction::Add)
273 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
274 LHS = BOp->getOperand(0);
275 RHS = ConstantExpr::getAdd(RHS, CI);
276 isNSW = isNUW = false;
278 // If the old 'LHS' was an input, add the new 'LHS' as an input.
279 if (std::count(InstInputs.begin(), InstInputs.end(), BOp)) {
280 RemoveInstInputs(BOp, InstInputs);
285 // See if the add simplifies away.
286 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD, DT)) {
287 // If we simplified the operands, the LHS is no longer an input, but Res
289 RemoveInstInputs(LHS, InstInputs);
290 return AddAsInput(Res);
293 // If we didn't modify the add, just return it.
294 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
297 // Otherwise, see if we have this add available somewhere.
298 for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
300 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI))
301 if (BO->getOpcode() == Instruction::Add &&
302 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
303 BO->getParent()->getParent() == CurBB->getParent() &&
304 (!DT || DT->dominates(BO->getParent(), PredBB)))
311 // Otherwise, we failed.
316 /// PHITranslateValue - PHI translate the current address up the CFG from
317 /// CurBB to Pred, updating our state to reflect any needed changes. If the
318 /// dominator tree DT is non-null, the translated value must dominate
319 /// PredBB. This returns true on failure and sets Addr to null.
320 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
321 const DominatorTree *DT) {
322 assert(Verify() && "Invalid PHITransAddr!");
323 Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
324 assert(Verify() && "Invalid PHITransAddr!");
327 // Make sure the value is live in the predecessor.
328 if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
329 if (!DT->dominates(Inst->getParent(), PredBB))
336 /// PHITranslateWithInsertion - PHI translate this value into the specified
337 /// predecessor block, inserting a computation of the value if it is
340 /// All newly created instructions are added to the NewInsts list. This
341 /// returns null on failure.
343 Value *PHITransAddr::
344 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
345 const DominatorTree &DT,
346 SmallVectorImpl<Instruction*> &NewInsts) {
347 unsigned NISize = NewInsts.size();
349 // Attempt to PHI translate with insertion.
350 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
352 // If successful, return the new value.
353 if (Addr) return Addr;
355 // If not, destroy any intermediate instructions inserted.
356 while (NewInsts.size() != NISize)
357 NewInsts.pop_back_val()->eraseFromParent();
362 /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
363 /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
364 /// block. All newly created instructions are added to the NewInsts list.
365 /// This returns null on failure.
367 Value *PHITransAddr::
368 InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
369 BasicBlock *PredBB, const DominatorTree &DT,
370 SmallVectorImpl<Instruction*> &NewInsts) {
371 // See if we have a version of this value already available and dominating
372 // PredBB. If so, there is no need to insert a new instance of it.
373 PHITransAddr Tmp(InVal, TD);
374 if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT))
375 return Tmp.getAddr();
377 // If we don't have an available version of this value, it must be an
379 Instruction *Inst = cast<Instruction>(InVal);
381 // Handle cast of PHI translatable value.
382 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
383 if (!Cast->isSafeToSpeculativelyExecute()) return 0;
384 Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
385 CurBB, PredBB, DT, NewInsts);
386 if (OpVal == 0) return 0;
388 // Otherwise insert a cast at the end of PredBB.
389 CastInst *New = CastInst::Create(Cast->getOpcode(),
390 OpVal, InVal->getType(),
391 InVal->getName()+".phi.trans.insert",
392 PredBB->getTerminator());
393 NewInsts.push_back(New);
397 // Handle getelementptr with at least one PHI operand.
398 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
399 SmallVector<Value*, 8> GEPOps;
400 BasicBlock *CurBB = GEP->getParent();
401 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
402 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
403 CurBB, PredBB, DT, NewInsts);
404 if (OpVal == 0) return 0;
405 GEPOps.push_back(OpVal);
408 GetElementPtrInst *Result =
409 GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(),
410 InVal->getName()+".phi.trans.insert",
411 PredBB->getTerminator());
412 Result->setIsInBounds(GEP->isInBounds());
413 NewInsts.push_back(Result);
418 // FIXME: This code works, but it is unclear that we actually want to insert
419 // a big chain of computation in order to make a value available in a block.
420 // This needs to be evaluated carefully to consider its cost trade offs.
422 // Handle add with a constant RHS.
423 if (Inst->getOpcode() == Instruction::Add &&
424 isa<ConstantInt>(Inst->getOperand(1))) {
425 // PHI translate the LHS.
426 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
427 CurBB, PredBB, DT, NewInsts);
428 if (OpVal == 0) return 0;
430 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
431 InVal->getName()+".phi.trans.insert",
432 PredBB->getTerminator());
433 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
434 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
435 NewInsts.push_back(Res);