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/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"
25 static bool CanPHITrans(Instruction *Inst) {
26 if (isa<PHINode>(Inst) ||
27 isa<GetElementPtrInst>(Inst))
30 if (isa<CastInst>(Inst) &&
31 isSafeToSpeculativelyExecute(Inst))
34 if (Inst->getOpcode() == Instruction::Add &&
35 isa<ConstantInt>(Inst->getOperand(1)))
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);
44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
45 void PHITransAddr::dump() const {
47 dbgs() << "PHITransAddr: null\n";
50 dbgs() << "PHITransAddr: " << *Addr << "\n";
51 for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
52 dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
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);
63 // If it's an instruction, it is either in Tmp or its operands recursively
65 SmallVectorImpl<Instruction*>::iterator Entry =
66 std::find(InstInputs.begin(), InstInputs.end(), I);
67 if (Entry != InstInputs.end()) {
68 InstInputs.erase(Entry);
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";
77 llvm_unreachable("Either something is missing from InstInputs or "
78 "CanPHITrans is wrong.");
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))
89 /// Verify - Check internal consistency of this data structure. If the
90 /// structure is valid, it returns true. If invalid, it prints errors and
92 bool PHITransAddr::Verify() const {
93 if (!Addr) return true;
95 SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
97 if (!VerifySubExpr(Addr, Tmp))
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.");
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);
123 static void RemoveInstInputs(Value *V,
124 SmallVectorImpl<Instruction*> &InstInputs) {
125 Instruction *I = dyn_cast<Instruction>(V);
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);
136 assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
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);
145 Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
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);
152 // Determine whether 'Inst' is an input to our PHI translatable expression.
154 std::find(InstInputs.begin(), InstInputs.end(), Inst) != InstInputs.end();
156 // Handle inputs instructions if needed.
158 if (Inst->getParent() != CurBB) {
159 // If it is an input defined in a different block, then it remains an
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.
167 // In either case, the instruction itself isn't an input any longer.
168 InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst));
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));
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))
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);
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.
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))
197 // Find an available version of this cast.
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()));
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)))
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;
224 AnyChanged |= GEPOp != GEP->getOperand(i);
225 GEPOps.push_back(GEPOp);
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);
236 return AddAsInput(V);
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 if (std::equal(GEPOps.begin(), GEPOps.end(), GEPI->op_begin()))
254 // Handle add with a constant RHS.
255 if (Inst->getOpcode() == Instruction::Add &&
256 isa<ConstantInt>(Inst->getOperand(1))) {
257 // PHI translate the LHS.
258 Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
259 bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
260 bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
262 Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
263 if (!LHS) return nullptr;
265 // If the PHI translated LHS is an add of a constant, fold the immediates.
266 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
267 if (BOp->getOpcode() == Instruction::Add)
268 if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
269 LHS = BOp->getOperand(0);
270 RHS = ConstantExpr::getAdd(RHS, CI);
271 isNSW = isNUW = false;
273 // If the old 'LHS' was an input, add the new 'LHS' as an input.
274 if (std::find(InstInputs.begin(), InstInputs.end(), BOp) !=
276 RemoveInstInputs(BOp, InstInputs);
281 // See if the add simplifies away.
282 if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, DL, TLI, DT, AC)) {
283 // If we simplified the operands, the LHS is no longer an input, but Res
285 RemoveInstInputs(LHS, InstInputs);
286 return AddAsInput(Res);
289 // If we didn't modify the add, just return it.
290 if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
293 // Otherwise, see if we have this add available somewhere.
294 for (User *U : LHS->users()) {
295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
296 if (BO->getOpcode() == Instruction::Add &&
297 BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
298 BO->getParent()->getParent() == CurBB->getParent() &&
299 (!DT || DT->dominates(BO->getParent(), PredBB)))
306 // Otherwise, we failed.
311 /// PHITranslateValue - PHI translate the current address up the CFG from
312 /// CurBB to Pred, updating our state to reflect any needed changes. If
313 /// 'MustDominate' is true, the translated value must dominate
314 /// PredBB. This returns true on failure and sets Addr to null.
315 bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
316 const DominatorTree *DT,
318 assert(DT || !MustDominate);
319 assert(Verify() && "Invalid PHITransAddr!");
320 if (DT && DT->isReachableFromEntry(PredBB))
322 PHITranslateSubExpr(Addr, CurBB, PredBB, MustDominate ? DT : nullptr);
325 assert(Verify() && "Invalid PHITransAddr!");
328 // Make sure the value is live in the predecessor.
329 if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
330 if (!DT->dominates(Inst->getParent(), PredBB))
333 return Addr == nullptr;
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, DL, AC);
374 if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT, /*MustDominate=*/true))
375 return Tmp.getAddr();
377 // We don't need to PHI translate values which aren't instructions.
378 auto *Inst = dyn_cast<Instruction>(InVal);
382 // Handle cast of PHI translatable value.
383 if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
384 if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
385 Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
386 CurBB, PredBB, DT, NewInsts);
387 if (!OpVal) return nullptr;
389 // Otherwise insert a cast at the end of PredBB.
390 CastInst *New = CastInst::Create(Cast->getOpcode(), OpVal, InVal->getType(),
391 InVal->getName() + ".phi.trans.insert",
392 PredBB->getTerminator());
393 New->setDebugLoc(Inst->getDebugLoc());
394 NewInsts.push_back(New);
398 // Handle getelementptr with at least one PHI operand.
399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
400 SmallVector<Value*, 8> GEPOps;
401 BasicBlock *CurBB = GEP->getParent();
402 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
403 Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
404 CurBB, PredBB, DT, NewInsts);
405 if (!OpVal) return nullptr;
406 GEPOps.push_back(OpVal);
409 GetElementPtrInst *Result = GetElementPtrInst::Create(
410 GEP->getSourceElementType(), GEPOps[0], makeArrayRef(GEPOps).slice(1),
411 InVal->getName() + ".phi.trans.insert", PredBB->getTerminator());
412 Result->setDebugLoc(Inst->getDebugLoc());
413 Result->setIsInBounds(GEP->isInBounds());
414 NewInsts.push_back(Result);
419 // FIXME: This code works, but it is unclear that we actually want to insert
420 // a big chain of computation in order to make a value available in a block.
421 // This needs to be evaluated carefully to consider its cost trade offs.
423 // Handle add with a constant RHS.
424 if (Inst->getOpcode() == Instruction::Add &&
425 isa<ConstantInt>(Inst->getOperand(1))) {
426 // PHI translate the LHS.
427 Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
428 CurBB, PredBB, DT, NewInsts);
429 if (OpVal == 0) return 0;
431 BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
432 InVal->getName()+".phi.trans.insert",
433 PredBB->getTerminator());
434 Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
435 Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
436 NewInsts.push_back(Res);