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