1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
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 Correlated Value Propagation pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LazyValueInfo.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/PassManager.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include <cassert>
48 #include <utility>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "correlated-value-propagation"
53 
54 STATISTIC(NumPhis,      "Number of phis propagated");
55 STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value");
56 STATISTIC(NumSelects,   "Number of selects propagated");
57 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
58 STATISTIC(NumCmps,      "Number of comparisons propagated");
59 STATISTIC(NumReturns,   "Number of return values propagated");
60 STATISTIC(NumDeadCases, "Number of switch cases removed");
61 STATISTIC(NumSDivs,     "Number of sdiv converted to udiv");
62 STATISTIC(NumUDivs,     "Number of udivs whose width was decreased");
63 STATISTIC(NumAShrs,     "Number of ashr converted to lshr");
64 STATISTIC(NumSRems,     "Number of srem converted to urem");
65 STATISTIC(NumOverflows, "Number of overflow checks removed");
66 STATISTIC(NumSaturating,
67     "Number of saturating arithmetics converted to normal arithmetics");
68 
69 static cl::opt<bool> DontAddNoWrapFlags("cvp-dont-add-nowrap-flags", cl::init(false));
70 
71 namespace {
72 
73   class CorrelatedValuePropagation : public FunctionPass {
74   public:
75     static char ID;
76 
77     CorrelatedValuePropagation(): FunctionPass(ID) {
78      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
79     }
80 
81     bool runOnFunction(Function &F) override;
82 
83     void getAnalysisUsage(AnalysisUsage &AU) const override {
84       AU.addRequired<DominatorTreeWrapperPass>();
85       AU.addRequired<LazyValueInfoWrapperPass>();
86       AU.addPreserved<GlobalsAAWrapperPass>();
87       AU.addPreserved<DominatorTreeWrapperPass>();
88       AU.addPreserved<LazyValueInfoWrapperPass>();
89     }
90   };
91 
92 } // end anonymous namespace
93 
94 char CorrelatedValuePropagation::ID = 0;
95 
96 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
97                 "Value Propagation", false, false)
98 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
99 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
100 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
101                 "Value Propagation", false, false)
102 
103 // Public interface to the Value Propagation pass
104 Pass *llvm::createCorrelatedValuePropagationPass() {
105   return new CorrelatedValuePropagation();
106 }
107 
108 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
109   if (S->getType()->isVectorTy()) return false;
110   if (isa<Constant>(S->getOperand(0))) return false;
111 
112   Constant *C = LVI->getConstant(S->getCondition(), S->getParent(), S);
113   if (!C) return false;
114 
115   ConstantInt *CI = dyn_cast<ConstantInt>(C);
116   if (!CI) return false;
117 
118   Value *ReplaceWith = S->getTrueValue();
119   Value *Other = S->getFalseValue();
120   if (!CI->isOne()) std::swap(ReplaceWith, Other);
121   if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
122 
123   S->replaceAllUsesWith(ReplaceWith);
124   S->eraseFromParent();
125 
126   ++NumSelects;
127 
128   return true;
129 }
130 
131 /// Try to simplify a phi with constant incoming values that match the edge
132 /// values of a non-constant value on all other edges:
133 /// bb0:
134 ///   %isnull = icmp eq i8* %x, null
135 ///   br i1 %isnull, label %bb2, label %bb1
136 /// bb1:
137 ///   br label %bb2
138 /// bb2:
139 ///   %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ]
140 /// -->
141 ///   %r = %x
142 static bool simplifyCommonValuePhi(PHINode *P, LazyValueInfo *LVI,
143                                    DominatorTree *DT) {
144   // Collect incoming constants and initialize possible common value.
145   SmallVector<std::pair<Constant *, unsigned>, 4> IncomingConstants;
146   Value *CommonValue = nullptr;
147   for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
148     Value *Incoming = P->getIncomingValue(i);
149     if (auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
150       IncomingConstants.push_back(std::make_pair(IncomingConstant, i));
151     } else if (!CommonValue) {
152       // The potential common value is initialized to the first non-constant.
153       CommonValue = Incoming;
154     } else if (Incoming != CommonValue) {
155       // There can be only one non-constant common value.
156       return false;
157     }
158   }
159 
160   if (!CommonValue || IncomingConstants.empty())
161     return false;
162 
163   // The common value must be valid in all incoming blocks.
164   BasicBlock *ToBB = P->getParent();
165   if (auto *CommonInst = dyn_cast<Instruction>(CommonValue))
166     if (!DT->dominates(CommonInst, ToBB))
167       return false;
168 
169   // We have a phi with exactly 1 variable incoming value and 1 or more constant
170   // incoming values. See if all constant incoming values can be mapped back to
171   // the same incoming variable value.
172   for (auto &IncomingConstant : IncomingConstants) {
173     Constant *C = IncomingConstant.first;
174     BasicBlock *IncomingBB = P->getIncomingBlock(IncomingConstant.second);
175     if (C != LVI->getConstantOnEdge(CommonValue, IncomingBB, ToBB, P))
176       return false;
177   }
178 
179   // All constant incoming values map to the same variable along the incoming
180   // edges of the phi. The phi is unnecessary.
181   P->replaceAllUsesWith(CommonValue);
182   P->eraseFromParent();
183   ++NumPhiCommon;
184   return true;
185 }
186 
187 static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT,
188                        const SimplifyQuery &SQ) {
189   bool Changed = false;
190 
191   BasicBlock *BB = P->getParent();
192   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
193     Value *Incoming = P->getIncomingValue(i);
194     if (isa<Constant>(Incoming)) continue;
195 
196     Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
197 
198     // Look if the incoming value is a select with a scalar condition for which
199     // LVI can tells us the value. In that case replace the incoming value with
200     // the appropriate value of the select. This often allows us to remove the
201     // select later.
202     if (!V) {
203       SelectInst *SI = dyn_cast<SelectInst>(Incoming);
204       if (!SI) continue;
205 
206       Value *Condition = SI->getCondition();
207       if (!Condition->getType()->isVectorTy()) {
208         if (Constant *C = LVI->getConstantOnEdge(
209                 Condition, P->getIncomingBlock(i), BB, P)) {
210           if (C->isOneValue()) {
211             V = SI->getTrueValue();
212           } else if (C->isZeroValue()) {
213             V = SI->getFalseValue();
214           }
215           // Once LVI learns to handle vector types, we could also add support
216           // for vector type constants that are not all zeroes or all ones.
217         }
218       }
219 
220       // Look if the select has a constant but LVI tells us that the incoming
221       // value can never be that constant. In that case replace the incoming
222       // value with the other value of the select. This often allows us to
223       // remove the select later.
224       if (!V) {
225         Constant *C = dyn_cast<Constant>(SI->getFalseValue());
226         if (!C) continue;
227 
228         if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
229               P->getIncomingBlock(i), BB, P) !=
230             LazyValueInfo::False)
231           continue;
232         V = SI->getTrueValue();
233       }
234 
235       LLVM_DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
236     }
237 
238     P->setIncomingValue(i, V);
239     Changed = true;
240   }
241 
242   if (Value *V = SimplifyInstruction(P, SQ)) {
243     P->replaceAllUsesWith(V);
244     P->eraseFromParent();
245     Changed = true;
246   }
247 
248   if (!Changed)
249     Changed = simplifyCommonValuePhi(P, LVI, DT);
250 
251   if (Changed)
252     ++NumPhis;
253 
254   return Changed;
255 }
256 
257 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
258   Value *Pointer = nullptr;
259   if (LoadInst *L = dyn_cast<LoadInst>(I))
260     Pointer = L->getPointerOperand();
261   else
262     Pointer = cast<StoreInst>(I)->getPointerOperand();
263 
264   if (isa<Constant>(Pointer)) return false;
265 
266   Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
267   if (!C) return false;
268 
269   ++NumMemAccess;
270   I->replaceUsesOfWith(Pointer, C);
271   return true;
272 }
273 
274 /// See if LazyValueInfo's ability to exploit edge conditions or range
275 /// information is sufficient to prove this comparison. Even for local
276 /// conditions, this can sometimes prove conditions instcombine can't by
277 /// exploiting range information.
278 static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
279   Value *Op0 = Cmp->getOperand(0);
280   auto *C = dyn_cast<Constant>(Cmp->getOperand(1));
281   if (!C)
282     return false;
283 
284   // As a policy choice, we choose not to waste compile time on anything where
285   // the comparison is testing local values.  While LVI can sometimes reason
286   // about such cases, it's not its primary purpose.  We do make sure to do
287   // the block local query for uses from terminator instructions, but that's
288   // handled in the code for each terminator.
289   auto *I = dyn_cast<Instruction>(Op0);
290   if (I && I->getParent() == Cmp->getParent())
291     return false;
292 
293   LazyValueInfo::Tristate Result =
294       LVI->getPredicateAt(Cmp->getPredicate(), Op0, C, Cmp);
295   if (Result == LazyValueInfo::Unknown)
296     return false;
297 
298   ++NumCmps;
299   Constant *TorF = ConstantInt::get(Type::getInt1Ty(Cmp->getContext()), Result);
300   Cmp->replaceAllUsesWith(TorF);
301   Cmp->eraseFromParent();
302   return true;
303 }
304 
305 /// Simplify a switch instruction by removing cases which can never fire. If the
306 /// uselessness of a case could be determined locally then constant propagation
307 /// would already have figured it out. Instead, walk the predecessors and
308 /// statically evaluate cases based on information available on that edge. Cases
309 /// that cannot fire no matter what the incoming edge can safely be removed. If
310 /// a case fires on every incoming edge then the entire switch can be removed
311 /// and replaced with a branch to the case destination.
312 static bool processSwitch(SwitchInst *I, LazyValueInfo *LVI,
313                           DominatorTree *DT) {
314   DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
315   Value *Cond = I->getCondition();
316   BasicBlock *BB = I->getParent();
317 
318   // If the condition was defined in same block as the switch then LazyValueInfo
319   // currently won't say anything useful about it, though in theory it could.
320   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
321     return false;
322 
323   // If the switch is unreachable then trying to improve it is a waste of time.
324   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
325   if (PB == PE) return false;
326 
327   // Analyse each switch case in turn.
328   bool Changed = false;
329   DenseMap<BasicBlock*, int> SuccessorsCount;
330   for (auto *Succ : successors(BB))
331     SuccessorsCount[Succ]++;
332 
333   { // Scope for SwitchInstProfUpdateWrapper. It must not live during
334     // ConstantFoldTerminator() as the underlying SwitchInst can be changed.
335     SwitchInstProfUpdateWrapper SI(*I);
336 
337     for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
338       ConstantInt *Case = CI->getCaseValue();
339 
340       // Check to see if the switch condition is equal to/not equal to the case
341       // value on every incoming edge, equal/not equal being the same each time.
342       LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
343       for (pred_iterator PI = PB; PI != PE; ++PI) {
344         // Is the switch condition equal to the case value?
345         LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
346                                                                 Cond, Case, *PI,
347                                                                 BB, SI);
348         // Give up on this case if nothing is known.
349         if (Value == LazyValueInfo::Unknown) {
350           State = LazyValueInfo::Unknown;
351           break;
352         }
353 
354         // If this was the first edge to be visited, record that all other edges
355         // need to give the same result.
356         if (PI == PB) {
357           State = Value;
358           continue;
359         }
360 
361         // If this case is known to fire for some edges and known not to fire for
362         // others then there is nothing we can do - give up.
363         if (Value != State) {
364           State = LazyValueInfo::Unknown;
365           break;
366         }
367       }
368 
369       if (State == LazyValueInfo::False) {
370         // This case never fires - remove it.
371         BasicBlock *Succ = CI->getCaseSuccessor();
372         Succ->removePredecessor(BB);
373         CI = SI.removeCase(CI);
374         CE = SI->case_end();
375 
376         // The condition can be modified by removePredecessor's PHI simplification
377         // logic.
378         Cond = SI->getCondition();
379 
380         ++NumDeadCases;
381         Changed = true;
382         if (--SuccessorsCount[Succ] == 0)
383           DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, Succ}});
384         continue;
385       }
386       if (State == LazyValueInfo::True) {
387         // This case always fires.  Arrange for the switch to be turned into an
388         // unconditional branch by replacing the switch condition with the case
389         // value.
390         SI->setCondition(Case);
391         NumDeadCases += SI->getNumCases();
392         Changed = true;
393         break;
394       }
395 
396       // Increment the case iterator since we didn't delete it.
397       ++CI;
398     }
399   }
400 
401   if (Changed)
402     // If the switch has been simplified to the point where it can be replaced
403     // by a branch then do so now.
404     ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false,
405                            /*TLI = */ nullptr, &DTU);
406   return Changed;
407 }
408 
409 // See if we can prove that the given binary op intrinsic will not overflow.
410 static bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI) {
411   ConstantRange LRange = LVI->getConstantRange(
412       BO->getLHS(), BO->getParent(), BO);
413   ConstantRange RRange = LVI->getConstantRange(
414       BO->getRHS(), BO->getParent(), BO);
415   ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
416       BO->getBinaryOp(), RRange, BO->getNoWrapKind());
417   return NWRegion.contains(LRange);
418 }
419 
420 static void processOverflowIntrinsic(WithOverflowInst *WO) {
421   IRBuilder<> B(WO);
422   Value *NewOp = B.CreateBinOp(
423       WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), WO->getName());
424   // Constant-folding could have happened.
425   if (auto *Inst = dyn_cast<Instruction>(NewOp)) {
426     if (WO->isSigned())
427       Inst->setHasNoSignedWrap();
428     else
429       Inst->setHasNoUnsignedWrap();
430   }
431 
432   Value *NewI = B.CreateInsertValue(UndefValue::get(WO->getType()), NewOp, 0);
433   NewI = B.CreateInsertValue(NewI, ConstantInt::getFalse(WO->getContext()), 1);
434   WO->replaceAllUsesWith(NewI);
435   WO->eraseFromParent();
436   ++NumOverflows;
437 }
438 
439 static void processSaturatingInst(SaturatingInst *SI) {
440   BinaryOperator *BinOp = BinaryOperator::Create(
441       SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
442   BinOp->setDebugLoc(SI->getDebugLoc());
443   if (SI->isSigned())
444     BinOp->setHasNoSignedWrap();
445   else
446     BinOp->setHasNoUnsignedWrap();
447 
448   SI->replaceAllUsesWith(BinOp);
449   SI->eraseFromParent();
450   ++NumSaturating;
451 }
452 
453 /// Infer nonnull attributes for the arguments at the specified callsite.
454 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) {
455   SmallVector<unsigned, 4> ArgNos;
456   unsigned ArgNo = 0;
457 
458   if (auto *WO = dyn_cast<WithOverflowInst>(CS.getInstruction())) {
459     if (WO->getLHS()->getType()->isIntegerTy() && willNotOverflow(WO, LVI)) {
460       processOverflowIntrinsic(WO);
461       return true;
462     }
463   }
464 
465   if (auto *SI = dyn_cast<SaturatingInst>(CS.getInstruction())) {
466     if (SI->getType()->isIntegerTy() && willNotOverflow(SI, LVI)) {
467       processSaturatingInst(SI);
468       return true;
469     }
470   }
471 
472   // Deopt bundle operands are intended to capture state with minimal
473   // perturbance of the code otherwise.  If we can find a constant value for
474   // any such operand and remove a use of the original value, that's
475   // desireable since it may allow further optimization of that value (e.g. via
476   // single use rules in instcombine).  Since deopt uses tend to,
477   // idiomatically, appear along rare conditional paths, it's reasonable likely
478   // we may have a conditional fact with which LVI can fold.
479   if (auto DeoptBundle = CS.getOperandBundle(LLVMContext::OB_deopt)) {
480     bool Progress = false;
481     for (const Use &ConstU : DeoptBundle->Inputs) {
482       Use &U = const_cast<Use&>(ConstU);
483       Value *V = U.get();
484       if (V->getType()->isVectorTy()) continue;
485       if (isa<Constant>(V)) continue;
486 
487       Constant *C = LVI->getConstant(V, CS.getParent(), CS.getInstruction());
488       if (!C) continue;
489       U.set(C);
490       Progress = true;
491     }
492     if (Progress)
493       return true;
494   }
495 
496   for (Value *V : CS.args()) {
497     PointerType *Type = dyn_cast<PointerType>(V->getType());
498     // Try to mark pointer typed parameters as non-null.  We skip the
499     // relatively expensive analysis for constants which are obviously either
500     // null or non-null to start with.
501     if (Type && !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
502         !isa<Constant>(V) &&
503         LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
504                             ConstantPointerNull::get(Type),
505                             CS.getInstruction()) == LazyValueInfo::False)
506       ArgNos.push_back(ArgNo);
507     ArgNo++;
508   }
509 
510   assert(ArgNo == CS.arg_size() && "sanity check");
511 
512   if (ArgNos.empty())
513     return false;
514 
515   AttributeList AS = CS.getAttributes();
516   LLVMContext &Ctx = CS.getInstruction()->getContext();
517   AS = AS.addParamAttribute(Ctx, ArgNos,
518                             Attribute::get(Ctx, Attribute::NonNull));
519   CS.setAttributes(AS);
520 
521   return true;
522 }
523 
524 static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) {
525   Constant *Zero = ConstantInt::get(SDI->getType(), 0);
526   for (Value *O : SDI->operands()) {
527     auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI);
528     if (Result != LazyValueInfo::True)
529       return false;
530   }
531   return true;
532 }
533 
534 /// Try to shrink a udiv/urem's width down to the smallest power of two that's
535 /// sufficient to contain its operands.
536 static bool processUDivOrURem(BinaryOperator *Instr, LazyValueInfo *LVI) {
537   assert(Instr->getOpcode() == Instruction::UDiv ||
538          Instr->getOpcode() == Instruction::URem);
539   if (Instr->getType()->isVectorTy())
540     return false;
541 
542   // Find the smallest power of two bitwidth that's sufficient to hold Instr's
543   // operands.
544   auto OrigWidth = Instr->getType()->getIntegerBitWidth();
545   ConstantRange OperandRange(OrigWidth, /*isFullSet=*/false);
546   for (Value *Operand : Instr->operands()) {
547     OperandRange = OperandRange.unionWith(
548         LVI->getConstantRange(Operand, Instr->getParent()));
549   }
550   // Don't shrink below 8 bits wide.
551   unsigned NewWidth = std::max<unsigned>(
552       PowerOf2Ceil(OperandRange.getUnsignedMax().getActiveBits()), 8);
553   // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
554   // two.
555   if (NewWidth >= OrigWidth)
556     return false;
557 
558   ++NumUDivs;
559   IRBuilder<> B{Instr};
560   auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth);
561   auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
562                                      Instr->getName() + ".lhs.trunc");
563   auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
564                                      Instr->getName() + ".rhs.trunc");
565   auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
566   auto *Zext = B.CreateZExt(BO, Instr->getType(), Instr->getName() + ".zext");
567   if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
568     if (BinOp->getOpcode() == Instruction::UDiv)
569       BinOp->setIsExact(Instr->isExact());
570 
571   Instr->replaceAllUsesWith(Zext);
572   Instr->eraseFromParent();
573   return true;
574 }
575 
576 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
577   if (SDI->getType()->isVectorTy() || !hasPositiveOperands(SDI, LVI))
578     return false;
579 
580   ++NumSRems;
581   auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1),
582                                         SDI->getName(), SDI);
583   BO->setDebugLoc(SDI->getDebugLoc());
584   SDI->replaceAllUsesWith(BO);
585   SDI->eraseFromParent();
586 
587   // Try to process our new urem.
588   processUDivOrURem(BO, LVI);
589 
590   return true;
591 }
592 
593 /// See if LazyValueInfo's ability to exploit edge conditions or range
594 /// information is sufficient to prove the both operands of this SDiv are
595 /// positive.  If this is the case, replace the SDiv with a UDiv. Even for local
596 /// conditions, this can sometimes prove conditions instcombine can't by
597 /// exploiting range information.
598 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
599   if (SDI->getType()->isVectorTy() || !hasPositiveOperands(SDI, LVI))
600     return false;
601 
602   ++NumSDivs;
603   auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1),
604                                         SDI->getName(), SDI);
605   BO->setDebugLoc(SDI->getDebugLoc());
606   BO->setIsExact(SDI->isExact());
607   SDI->replaceAllUsesWith(BO);
608   SDI->eraseFromParent();
609 
610   // Try to simplify our new udiv.
611   processUDivOrURem(BO, LVI);
612 
613   return true;
614 }
615 
616 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
617   if (SDI->getType()->isVectorTy())
618     return false;
619 
620   Constant *Zero = ConstantInt::get(SDI->getType(), 0);
621   if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) !=
622       LazyValueInfo::True)
623     return false;
624 
625   ++NumAShrs;
626   auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
627                                         SDI->getName(), SDI);
628   BO->setDebugLoc(SDI->getDebugLoc());
629   BO->setIsExact(SDI->isExact());
630   SDI->replaceAllUsesWith(BO);
631   SDI->eraseFromParent();
632 
633   return true;
634 }
635 
636 static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI) {
637   using OBO = OverflowingBinaryOperator;
638 
639   if (DontAddNoWrapFlags)
640     return false;
641 
642   if (BinOp->getType()->isVectorTy())
643     return false;
644 
645   bool NSW = BinOp->hasNoSignedWrap();
646   bool NUW = BinOp->hasNoUnsignedWrap();
647   if (NSW && NUW)
648     return false;
649 
650   BasicBlock *BB = BinOp->getParent();
651 
652   Value *LHS = BinOp->getOperand(0);
653   Value *RHS = BinOp->getOperand(1);
654 
655   ConstantRange LRange = LVI->getConstantRange(LHS, BB, BinOp);
656   ConstantRange RRange = LVI->getConstantRange(RHS, BB, BinOp);
657 
658   bool Changed = false;
659   if (!NUW) {
660     ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
661         BinOp->getOpcode(), RRange, OBO::NoUnsignedWrap);
662     bool NewNUW = NUWRange.contains(LRange);
663     BinOp->setHasNoUnsignedWrap(NewNUW);
664     Changed |= NewNUW;
665   }
666   if (!NSW) {
667     ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
668         BinOp->getOpcode(), RRange, OBO::NoSignedWrap);
669     bool NewNSW = NSWRange.contains(LRange);
670     BinOp->setHasNoSignedWrap(NewNSW);
671     Changed |= NewNSW;
672   }
673 
674   return Changed;
675 }
676 
677 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
678   if (Constant *C = LVI->getConstant(V, At->getParent(), At))
679     return C;
680 
681   // TODO: The following really should be sunk inside LVI's core algorithm, or
682   // at least the outer shims around such.
683   auto *C = dyn_cast<CmpInst>(V);
684   if (!C) return nullptr;
685 
686   Value *Op0 = C->getOperand(0);
687   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
688   if (!Op1) return nullptr;
689 
690   LazyValueInfo::Tristate Result =
691     LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
692   if (Result == LazyValueInfo::Unknown)
693     return nullptr;
694 
695   return (Result == LazyValueInfo::True) ?
696     ConstantInt::getTrue(C->getContext()) :
697     ConstantInt::getFalse(C->getContext());
698 }
699 
700 static bool runImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT,
701                     const SimplifyQuery &SQ) {
702   bool FnChanged = false;
703   // Visiting in a pre-order depth-first traversal causes us to simplify early
704   // blocks before querying later blocks (which require us to analyze early
705   // blocks).  Eagerly simplifying shallow blocks means there is strictly less
706   // work to do for deep blocks.  This also means we don't visit unreachable
707   // blocks.
708   for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
709     bool BBChanged = false;
710     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
711       Instruction *II = &*BI++;
712       switch (II->getOpcode()) {
713       case Instruction::Select:
714         BBChanged |= processSelect(cast<SelectInst>(II), LVI);
715         break;
716       case Instruction::PHI:
717         BBChanged |= processPHI(cast<PHINode>(II), LVI, DT, SQ);
718         break;
719       case Instruction::ICmp:
720       case Instruction::FCmp:
721         BBChanged |= processCmp(cast<CmpInst>(II), LVI);
722         break;
723       case Instruction::Load:
724       case Instruction::Store:
725         BBChanged |= processMemAccess(II, LVI);
726         break;
727       case Instruction::Call:
728       case Instruction::Invoke:
729         BBChanged |= processCallSite(CallSite(II), LVI);
730         break;
731       case Instruction::SRem:
732         BBChanged |= processSRem(cast<BinaryOperator>(II), LVI);
733         break;
734       case Instruction::SDiv:
735         BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI);
736         break;
737       case Instruction::UDiv:
738       case Instruction::URem:
739         BBChanged |= processUDivOrURem(cast<BinaryOperator>(II), LVI);
740         break;
741       case Instruction::AShr:
742         BBChanged |= processAShr(cast<BinaryOperator>(II), LVI);
743         break;
744       case Instruction::Add:
745       case Instruction::Sub:
746         BBChanged |= processBinOp(cast<BinaryOperator>(II), LVI);
747         break;
748       }
749     }
750 
751     Instruction *Term = BB->getTerminator();
752     switch (Term->getOpcode()) {
753     case Instruction::Switch:
754       BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI, DT);
755       break;
756     case Instruction::Ret: {
757       auto *RI = cast<ReturnInst>(Term);
758       // Try to determine the return value if we can.  This is mainly here to
759       // simplify the writing of unit tests, but also helps to enable IPO by
760       // constant folding the return values of callees.
761       auto *RetVal = RI->getReturnValue();
762       if (!RetVal) break; // handle "ret void"
763       if (isa<Constant>(RetVal)) break; // nothing to do
764       if (auto *C = getConstantAt(RetVal, RI, LVI)) {
765         ++NumReturns;
766         RI->replaceUsesOfWith(RetVal, C);
767         BBChanged = true;
768       }
769     }
770     }
771 
772     FnChanged |= BBChanged;
773   }
774 
775   return FnChanged;
776 }
777 
778 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
779   if (skipFunction(F))
780     return false;
781 
782   LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
783   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
784 
785   return runImpl(F, LVI, DT, getBestSimplifyQuery(*this, F));
786 }
787 
788 PreservedAnalyses
789 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
790   LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
791   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
792 
793   bool Changed = runImpl(F, LVI, DT, getBestSimplifyQuery(AM, F));
794 
795   if (!Changed)
796     return PreservedAnalyses::all();
797   PreservedAnalyses PA;
798   PA.preserve<GlobalsAA>();
799   PA.preserve<DominatorTreeAnalysis>();
800   PA.preserve<LazyValueAnalysis>();
801   return PA;
802 }
803