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