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/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
22 static bool CanPHITrans(Instruction *Inst) {
23 if (isa<PHINode>(Inst) ||
24 isa<GetElementPtrInst>(Inst))
27 if (isa<CastInst>(Inst) &&
28 Inst->isSafeToSpeculativelyExecute())
31 if (Inst->getOpcode() == Instruction::Add &&
32 isa<ConstantInt>(Inst->getOperand(1)))
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);
41 void PHITransAddr::dump() const {
43 dbgs() << "PHITransAddr: null\n";
46 dbgs() << "PHITransAddr: " << *Addr << "\n";
47 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
48 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
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;
58 // If it's an instruction, it is either in Tmp or its operands recursively
60 SmallVectorImpl<Instruction*>::iterator Entry =
61 std::find(InstInputs.begin(), InstInputs.end(), I);
62 if (Entry != InstInputs.end()) {
63 InstInputs.erase(Entry);
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";
72 llvm_unreachable("Either something is missing from InstInputs or "
73 "CanPHITrans is wrong.");
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))
85 /// Verify - Check internal consistency of this data structure. If the
86 /// structure is valid, it returns true. If invalid, it prints errors and
88 bool PHITransAddr::Verify() const {
89 if (Addr == 0) return true;
91 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
93 if (!VerifySubExpr(Addr, Tmp))
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.");
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);
120 static void RemoveInstInputs(Value *V,
121 SmallVectorImpl<Instruction*> &InstInputs) {
122 Instruction *I = dyn_cast<Instruction>(V);
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);
133 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
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);
142 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
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;
149 // Determine whether 'Inst' is an input to our PHI translatable expression.
150 bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
152 // Handle inputs instructions if needed.
154 if (Inst->getParent() != CurBB) {
155 // If it is an input defined in a different block, then it remains an
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.
163 // In either case, the instruction itself isn't an input any longer.
164 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
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));
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))
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);
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.
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))
193 // Find an available version of this cast.
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()));
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();
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)))
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;
221 AnyChanged |= GEPOp != GEP->getOperand(i);
222 GEPOps.push_back(GEPOp);
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);
233 return AddAsInput(V);
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();
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]) {
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();
266 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
267 if (LHS == 0) return 0;
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;
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);
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
288 RemoveInstInputs(LHS, InstInputs);
289 return AddAsInput(Res);
292 // If we didn't modify the add, just return it.
293 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
296 // Otherwise, see if we have this add available somewhere.
297 for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end();
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)))
310 // Otherwise, we failed.
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!");
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))
335 /// PHITranslateWithInsertion - PHI translate this value into the specified
336 /// predecessor block, inserting a computation of the value if it is
339 /// All newly created instructions are added to the NewInsts list. This
340 /// returns null on failure.
342 Value *PHITransAddr::
343 PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
344 const DominatorTree &DT,
345 SmallVectorImpl<Instruction*> &NewInsts) {
346 unsigned NISize = NewInsts.size();
348 // Attempt to PHI translate with insertion.
349 Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
351 // If successful, return the new value.
352 if (Addr) return Addr;
354 // If not, destroy any intermediate instructions inserted.
355 while (NewInsts.size() != NISize)
356 NewInsts.pop_back_val()->eraseFromParent();
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.
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();
376 // If we don't have an available version of this value, it must be an
378 Instruction *Inst = cast<Instruction>(InVal);
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;
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);
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);
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);
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.
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;
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);