xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision a9d6a86b214e03fbaa68c10c482be2b9aea894ef)
1 //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
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 // Eliminate conditions based on constraints collected from dominating
10 // conditions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/ConstraintSystem.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/DebugCounter.h"
33 #include "llvm/Support/MathExtras.h"
34 
35 #include <cmath>
36 #include <string>
37 
38 using namespace llvm;
39 using namespace PatternMatch;
40 
41 #define DEBUG_TYPE "constraint-elimination"
42 
43 STATISTIC(NumCondsRemoved, "Number of instructions removed");
44 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
45               "Controls which conditions are eliminated");
46 
47 static cl::opt<unsigned>
48     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
49             cl::desc("Maximum number of rows to keep in constraint system"));
50 
51 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
52 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
53 
54 // A helper to multiply 2 signed integers where overflowing is allowed.
55 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
56   int64_t Result;
57   MulOverflow(A, B, Result);
58   return Result;
59 }
60 
61 // A helper to add 2 signed integers where overflowing is allowed.
62 static int64_t addWithOverflow(int64_t A, int64_t B) {
63   int64_t Result;
64   AddOverflow(A, B, Result);
65   return Result;
66 }
67 
68 namespace {
69 
70 class ConstraintInfo;
71 
72 struct StackEntry {
73   unsigned NumIn;
74   unsigned NumOut;
75   bool IsSigned = false;
76   /// Variables that can be removed from the system once the stack entry gets
77   /// removed.
78   SmallVector<Value *, 2> ValuesToRelease;
79 
80   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
81              SmallVector<Value *, 2> ValuesToRelease)
82       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
83         ValuesToRelease(ValuesToRelease) {}
84 };
85 
86 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
87 struct PreconditionTy {
88   CmpInst::Predicate Pred;
89   Value *Op0;
90   Value *Op1;
91 
92   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
93       : Pred(Pred), Op0(Op0), Op1(Op1) {}
94 };
95 
96 struct ConstraintTy {
97   SmallVector<int64_t, 8> Coefficients;
98   SmallVector<PreconditionTy, 2> Preconditions;
99 
100   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
101 
102   bool IsSigned = false;
103   bool IsEq = false;
104 
105   ConstraintTy() = default;
106 
107   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
108       : Coefficients(Coefficients), IsSigned(IsSigned) {}
109 
110   unsigned size() const { return Coefficients.size(); }
111 
112   unsigned empty() const { return Coefficients.empty(); }
113 
114   /// Returns true if all preconditions for this list of constraints are
115   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
116   bool isValid(const ConstraintInfo &Info) const;
117 };
118 
119 /// Wrapper encapsulating separate constraint systems and corresponding value
120 /// mappings for both unsigned and signed information. Facts are added to and
121 /// conditions are checked against the corresponding system depending on the
122 /// signed-ness of their predicates. While the information is kept separate
123 /// based on signed-ness, certain conditions can be transferred between the two
124 /// systems.
125 class ConstraintInfo {
126 
127   ConstraintSystem UnsignedCS;
128   ConstraintSystem SignedCS;
129 
130   const DataLayout &DL;
131 
132 public:
133   ConstraintInfo(const DataLayout &DL) : DL(DL) {}
134 
135   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
136     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
137   }
138   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
139     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
140   }
141 
142   ConstraintSystem &getCS(bool Signed) {
143     return Signed ? SignedCS : UnsignedCS;
144   }
145   const ConstraintSystem &getCS(bool Signed) const {
146     return Signed ? SignedCS : UnsignedCS;
147   }
148 
149   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
150   void popLastNVariables(bool Signed, unsigned N) {
151     getCS(Signed).popLastNVariables(N);
152   }
153 
154   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
155 
156   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
157                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
158 
159   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
160   /// constraints, using indices from the corresponding constraint system.
161   /// New variables that need to be added to the system are collected in
162   /// \p NewVariables.
163   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
164                              SmallVectorImpl<Value *> &NewVariables) const;
165 
166   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
167   /// constraints using getConstraint. Returns an empty constraint if the result
168   /// cannot be used to query the existing constraint system, e.g. because it
169   /// would require adding new variables. Also tries to convert signed
170   /// predicates to unsigned ones if possible to allow using the unsigned system
171   /// which increases the effectiveness of the signed <-> unsigned transfer
172   /// logic.
173   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
174                                        Value *Op1) const;
175 
176   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
177   /// system if \p Pred is signed/unsigned.
178   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
179                              unsigned NumIn, unsigned NumOut,
180                              SmallVectorImpl<StackEntry> &DFSInStack);
181 };
182 
183 /// Represents a (Coefficient * Variable) entry after IR decomposition.
184 struct DecompEntry {
185   int64_t Coefficient;
186   Value *Variable;
187   /// True if the variable is known positive in the current constraint.
188   bool IsKnownNonNegative;
189 
190   DecompEntry(int64_t Coefficient, Value *Variable,
191               bool IsKnownNonNegative = false)
192       : Coefficient(Coefficient), Variable(Variable),
193         IsKnownNonNegative(IsKnownNonNegative) {}
194 };
195 
196 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
197 struct Decomposition {
198   int64_t Offset = 0;
199   SmallVector<DecompEntry, 3> Vars;
200 
201   Decomposition(int64_t Offset) : Offset(Offset) {}
202   Decomposition(Value *V, bool IsKnownNonNegative = false) {
203     Vars.emplace_back(1, V, IsKnownNonNegative);
204   }
205   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
206       : Offset(Offset), Vars(Vars) {}
207 
208   void add(int64_t OtherOffset) {
209     Offset = addWithOverflow(Offset, OtherOffset);
210   }
211 
212   void add(const Decomposition &Other) {
213     add(Other.Offset);
214     append_range(Vars, Other.Vars);
215   }
216 
217   void mul(int64_t Factor) {
218     Offset = multiplyWithOverflow(Offset, Factor);
219     for (auto &Var : Vars)
220       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
221   }
222 };
223 
224 } // namespace
225 
226 static Decomposition decompose(Value *V,
227                                SmallVectorImpl<PreconditionTy> &Preconditions,
228                                bool IsSigned, const DataLayout &DL);
229 
230 static bool canUseSExt(ConstantInt *CI) {
231   const APInt &Val = CI->getValue();
232   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
233 }
234 
235 static Decomposition
236 decomposeGEP(GetElementPtrInst &GEP,
237              SmallVectorImpl<PreconditionTy> &Preconditions, bool IsSigned,
238              const DataLayout &DL) {
239   // Do not reason about pointers where the index size is larger than 64 bits,
240   // as the coefficients used to encode constraints are 64 bit integers.
241   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
242     return &GEP;
243 
244   if (!GEP.isInBounds())
245     return &GEP;
246 
247   assert(!IsSigned && "The logic below only supports decomposition for "
248                       "unsinged predicates at the moment.");
249   Type *PtrTy = GEP.getType()->getScalarType();
250   unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
251   MapVector<Value *, APInt> VariableOffsets;
252   APInt ConstantOffset(BitWidth, 0);
253   if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
254     return &GEP;
255 
256   // Handle the (gep (gep ....), C) case by incrementing the constant
257   // coefficient of the inner GEP, if C is a constant.
258   auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
259   if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) {
260     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
261     Result.add(ConstantOffset.getSExtValue());
262 
263     if (ConstantOffset.isNegative()) {
264       unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType());
265       int64_t ConstantOffsetI = ConstantOffset.getSExtValue();
266       if (ConstantOffsetI % Scale != 0)
267         return &GEP;
268       // Add pre-condition ensuring the GEP is increasing monotonically and
269       // can be de-composed.
270       // Both sides are normalized by being divided by Scale.
271       Preconditions.emplace_back(
272           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
273           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
274                            -1 * (ConstantOffsetI / Scale)));
275     }
276     return Result;
277   }
278 
279   Decomposition Result(ConstantOffset.getSExtValue(),
280                        DecompEntry(1, GEP.getPointerOperand()));
281   for (auto [Index, Scale] : VariableOffsets) {
282     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
283     IdxResult.mul(Scale.getSExtValue());
284     Result.add(IdxResult);
285 
286     // If Op0 is signed non-negative, the GEP is increasing monotonically and
287     // can be de-composed.
288     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
289       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
290                                  ConstantInt::get(Index->getType(), 0));
291   }
292   return Result;
293 }
294 
295 // Decomposes \p V into a constant offset + list of pairs { Coefficient,
296 // Variable } where Coefficient * Variable. The sum of the constant offset and
297 // pairs equals \p V.
298 static Decomposition decompose(Value *V,
299                                SmallVectorImpl<PreconditionTy> &Preconditions,
300                                bool IsSigned, const DataLayout &DL) {
301 
302   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
303                                                       bool IsSignedB) {
304     auto ResA = decompose(A, Preconditions, IsSigned, DL);
305     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
306     ResA.add(ResB);
307     return ResA;
308   };
309 
310   // Decompose \p V used with a signed predicate.
311   if (IsSigned) {
312     if (auto *CI = dyn_cast<ConstantInt>(V)) {
313       if (canUseSExt(CI))
314         return CI->getSExtValue();
315     }
316     Value *Op0;
317     Value *Op1;
318     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
319       return MergeResults(Op0, Op1, IsSigned);
320 
321     return V;
322   }
323 
324   if (auto *CI = dyn_cast<ConstantInt>(V)) {
325     if (CI->uge(MaxConstraintValue))
326       return V;
327     return int64_t(CI->getZExtValue());
328   }
329 
330   if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
331     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
332 
333   Value *Op0;
334   bool IsKnownNonNegative = false;
335   if (match(V, m_ZExt(m_Value(Op0)))) {
336     IsKnownNonNegative = true;
337     V = Op0;
338   }
339 
340   Value *Op1;
341   ConstantInt *CI;
342   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
343     return MergeResults(Op0, Op1, IsSigned);
344   }
345   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
346     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
347       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
348                                  ConstantInt::get(Op0->getType(), 0));
349     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
350       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
351                                  ConstantInt::get(Op1->getType(), 0));
352 
353     return MergeResults(Op0, Op1, IsSigned);
354   }
355 
356   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
357       canUseSExt(CI)) {
358     Preconditions.emplace_back(
359         CmpInst::ICMP_UGE, Op0,
360         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
361     return MergeResults(Op0, CI, true);
362   }
363 
364   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
365     int64_t Mult = int64_t(std::pow(int64_t(2), CI->getSExtValue()));
366     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
367     Result.mul(Mult);
368     return Result;
369   }
370 
371   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
372       (!CI->isNegative())) {
373     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
374     Result.mul(CI->getSExtValue());
375     return Result;
376   }
377 
378   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
379     return {-1 * CI->getSExtValue(), {{1, Op0}}};
380   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
381     return {0, {{1, Op0}, {-1, Op1}}};
382 
383   return {V, IsKnownNonNegative};
384 }
385 
386 ConstraintTy
387 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
388                               SmallVectorImpl<Value *> &NewVariables) const {
389   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
390   bool IsEq = false;
391   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
392   switch (Pred) {
393   case CmpInst::ICMP_UGT:
394   case CmpInst::ICMP_UGE:
395   case CmpInst::ICMP_SGT:
396   case CmpInst::ICMP_SGE: {
397     Pred = CmpInst::getSwappedPredicate(Pred);
398     std::swap(Op0, Op1);
399     break;
400   }
401   case CmpInst::ICMP_EQ:
402     if (match(Op1, m_Zero())) {
403       Pred = CmpInst::ICMP_ULE;
404     } else {
405       IsEq = true;
406       Pred = CmpInst::ICMP_ULE;
407     }
408     break;
409   case CmpInst::ICMP_NE:
410     if (!match(Op1, m_Zero()))
411       return {};
412     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
413     std::swap(Op0, Op1);
414     break;
415   default:
416     break;
417   }
418 
419   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
420       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
421     return {};
422 
423   SmallVector<PreconditionTy, 4> Preconditions;
424   bool IsSigned = CmpInst::isSigned(Pred);
425   auto &Value2Index = getValue2Index(IsSigned);
426   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
427                         Preconditions, IsSigned, DL);
428   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
429                         Preconditions, IsSigned, DL);
430   int64_t Offset1 = ADec.Offset;
431   int64_t Offset2 = BDec.Offset;
432   Offset1 *= -1;
433 
434   auto &VariablesA = ADec.Vars;
435   auto &VariablesB = BDec.Vars;
436 
437   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
438   // new entry to NewVariables.
439   DenseMap<Value *, unsigned> NewIndexMap;
440   auto GetOrAddIndex = [&Value2Index, &NewVariables,
441                         &NewIndexMap](Value *V) -> unsigned {
442     auto V2I = Value2Index.find(V);
443     if (V2I != Value2Index.end())
444       return V2I->second;
445     auto Insert =
446         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
447     if (Insert.second)
448       NewVariables.push_back(V);
449     return Insert.first->second;
450   };
451 
452   // Make sure all variables have entries in Value2Index or NewVariables.
453   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
454     GetOrAddIndex(KV.Variable);
455 
456   // Build result constraint, by first adding all coefficients from A and then
457   // subtracting all coefficients from B.
458   ConstraintTy Res(
459       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
460       IsSigned);
461   // Collect variables that are known to be positive in all uses in the
462   // constraint.
463   DenseMap<Value *, bool> KnownNonNegativeVariables;
464   Res.IsEq = IsEq;
465   auto &R = Res.Coefficients;
466   for (const auto &KV : VariablesA) {
467     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
468     auto I =
469         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
470     I.first->second &= KV.IsKnownNonNegative;
471   }
472 
473   for (const auto &KV : VariablesB) {
474     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
475     auto I =
476         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
477     I.first->second &= KV.IsKnownNonNegative;
478   }
479 
480   int64_t OffsetSum;
481   if (AddOverflow(Offset1, Offset2, OffsetSum))
482     return {};
483   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
484     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
485       return {};
486   R[0] = OffsetSum;
487   Res.Preconditions = std::move(Preconditions);
488 
489   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
490   // variables.
491   while (!NewVariables.empty()) {
492     int64_t Last = R.back();
493     if (Last != 0)
494       break;
495     R.pop_back();
496     Value *RemovedV = NewVariables.pop_back_val();
497     NewIndexMap.erase(RemovedV);
498   }
499 
500   // Add extra constraints for variables that are known positive.
501   for (auto &KV : KnownNonNegativeVariables) {
502     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
503                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
504       continue;
505     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
506     C[GetOrAddIndex(KV.first)] = -1;
507     Res.ExtraInfo.push_back(C);
508   }
509   return Res;
510 }
511 
512 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
513                                                      Value *Op0,
514                                                      Value *Op1) const {
515   // If both operands are known to be non-negative, change signed predicates to
516   // unsigned ones. This increases the reasoning effectiveness in combination
517   // with the signed <-> unsigned transfer logic.
518   if (CmpInst::isSigned(Pred) &&
519       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
520       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
521     Pred = CmpInst::getUnsignedPredicate(Pred);
522 
523   SmallVector<Value *> NewVariables;
524   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
525   if (R.IsEq || !NewVariables.empty())
526     return {};
527   return R;
528 }
529 
530 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
531   return Coefficients.size() > 0 &&
532          all_of(Preconditions, [&Info](const PreconditionTy &C) {
533            return Info.doesHold(C.Pred, C.Op0, C.Op1);
534          });
535 }
536 
537 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
538                               Value *B) const {
539   auto R = getConstraintForSolving(Pred, A, B);
540   return R.Preconditions.empty() && !R.empty() &&
541          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
542 }
543 
544 void ConstraintInfo::transferToOtherSystem(
545     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
546     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
547   // Check if we can combine facts from the signed and unsigned systems to
548   // derive additional facts.
549   if (!A->getType()->isIntegerTy())
550     return;
551   // FIXME: This currently depends on the order we add facts. Ideally we
552   // would first add all known facts and only then try to add additional
553   // facts.
554   switch (Pred) {
555   default:
556     break;
557   case CmpInst::ICMP_ULT:
558     //  If B is a signed positive constant, A >=s 0 and A <s B.
559     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
560       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
561               NumOut, DFSInStack);
562       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
563     }
564     break;
565   case CmpInst::ICMP_SLT:
566     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
567       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
568     break;
569   case CmpInst::ICMP_SGT:
570     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
571       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
572               NumOut, DFSInStack);
573     break;
574   case CmpInst::ICMP_SGE:
575     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
576       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
577     }
578     break;
579   }
580 }
581 
582 namespace {
583 /// Represents either
584 ///  * a condition that holds on entry to a block (=conditional fact)
585 ///  * an assume (=assume fact)
586 ///  * an instruction to simplify.
587 /// It also tracks the Dominator DFS in and out numbers for each entry.
588 struct FactOrCheck {
589   Instruction *Inst;
590   unsigned NumIn;
591   unsigned NumOut;
592   bool IsCheck;
593   bool Not;
594 
595   FactOrCheck(DomTreeNode *DTN, Instruction *Inst, bool IsCheck, bool Not)
596       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
597         IsCheck(IsCheck), Not(Not) {}
598 
599   static FactOrCheck getFact(DomTreeNode *DTN, Instruction *Inst,
600                              bool Not = false) {
601     return FactOrCheck(DTN, Inst, false, Not);
602   }
603 
604   static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *Inst) {
605     return FactOrCheck(DTN, Inst, true, false);
606   }
607 
608   bool isAssumeFact() const {
609     if (!IsCheck && isa<IntrinsicInst>(Inst)) {
610       assert(match(Inst, m_Intrinsic<Intrinsic::assume>()));
611       return true;
612     }
613     return false;
614   }
615 
616   bool isConditionFact() const { return !IsCheck && isa<CmpInst>(Inst); }
617 };
618 
619 /// Keep state required to build worklist.
620 struct State {
621   DominatorTree &DT;
622   SmallVector<FactOrCheck, 64> WorkList;
623 
624   State(DominatorTree &DT) : DT(DT) {}
625 
626   /// Process block \p BB and add known facts to work-list.
627   void addInfoFor(BasicBlock &BB);
628 
629   /// Returns true if we can add a known condition from BB to its successor
630   /// block Succ.
631   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
632     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
633   }
634 };
635 
636 } // namespace
637 
638 #ifndef NDEBUG
639 static void dumpWithNames(const ConstraintSystem &CS,
640                           DenseMap<Value *, unsigned> &Value2Index) {
641   SmallVector<std::string> Names(Value2Index.size(), "");
642   for (auto &KV : Value2Index) {
643     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
644   }
645   CS.dump(Names);
646 }
647 
648 static void dumpWithNames(ArrayRef<int64_t> C,
649                           DenseMap<Value *, unsigned> &Value2Index) {
650   ConstraintSystem CS;
651   CS.addVariableRowFill(C);
652   dumpWithNames(CS, Value2Index);
653 }
654 #endif
655 
656 void State::addInfoFor(BasicBlock &BB) {
657   // True as long as long as the current instruction is guaranteed to execute.
658   bool GuaranteedToExecute = true;
659   // Queue conditions and assumes.
660   for (Instruction &I : BB) {
661     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
662       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), Cmp));
663       continue;
664     }
665 
666     if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) {
667       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), &I));
668       continue;
669     }
670 
671     Value *Cond;
672     // For now, just handle assumes with a single compare as condition.
673     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
674         isa<ICmpInst>(Cond)) {
675       if (GuaranteedToExecute) {
676         // The assume is guaranteed to execute when BB is entered, hence Cond
677         // holds on entry to BB.
678         WorkList.emplace_back(FactOrCheck::getFact(DT.getNode(I.getParent()),
679                                                    cast<Instruction>(Cond)));
680       } else {
681         WorkList.emplace_back(
682             FactOrCheck::getFact(DT.getNode(I.getParent()), &I));
683       }
684     }
685     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
686   }
687 
688   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
689   if (!Br || !Br->isConditional())
690     return;
691 
692   Value *Cond = Br->getCondition();
693 
694   // If the condition is a chain of ORs/AND and the successor only has the
695   // current block as predecessor, queue conditions for the successor.
696   Value *Op0, *Op1;
697   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
698       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
699     bool IsOr = match(Cond, m_LogicalOr());
700     bool IsAnd = match(Cond, m_LogicalAnd());
701     // If there's a select that matches both AND and OR, we need to commit to
702     // one of the options. Arbitrarily pick OR.
703     if (IsOr && IsAnd)
704       IsAnd = false;
705 
706     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
707     if (canAddSuccessor(BB, Successor)) {
708       SmallVector<Value *> CondWorkList;
709       SmallPtrSet<Value *, 8> SeenCond;
710       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
711         if (SeenCond.insert(V).second)
712           CondWorkList.push_back(V);
713       };
714       QueueValue(Op1);
715       QueueValue(Op0);
716       while (!CondWorkList.empty()) {
717         Value *Cur = CondWorkList.pop_back_val();
718         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
719           WorkList.emplace_back(
720               FactOrCheck::getFact(DT.getNode(Successor), Cmp, IsOr));
721           continue;
722         }
723         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
724           QueueValue(Op1);
725           QueueValue(Op0);
726           continue;
727         }
728         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
729           QueueValue(Op1);
730           QueueValue(Op0);
731           continue;
732         }
733       }
734     }
735     return;
736   }
737 
738   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
739   if (!CmpI)
740     return;
741   if (canAddSuccessor(BB, Br->getSuccessor(0)))
742     WorkList.emplace_back(
743         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(0)), CmpI));
744   if (canAddSuccessor(BB, Br->getSuccessor(1)))
745     WorkList.emplace_back(
746         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(1)), CmpI, true));
747 }
748 
749 static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info) {
750   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
751 
752   CmpInst::Predicate Pred = Cmp->getPredicate();
753   Value *A = Cmp->getOperand(0);
754   Value *B = Cmp->getOperand(1);
755 
756   auto R = Info.getConstraintForSolving(Pred, A, B);
757   if (R.empty() || !R.isValid(Info)){
758     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
759     return false;
760   }
761 
762   auto &CSToUse = Info.getCS(R.IsSigned);
763 
764   // If there was extra information collected during decomposition, apply
765   // it now and remove it immediately once we are done with reasoning
766   // about the constraint.
767   for (auto &Row : R.ExtraInfo)
768     CSToUse.addVariableRow(Row);
769   auto InfoRestorer = make_scope_exit([&]() {
770     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
771       CSToUse.popLastConstraint();
772   });
773 
774   bool Changed = false;
775   if (CSToUse.isConditionImplied(R.Coefficients)) {
776     if (!DebugCounter::shouldExecute(EliminatedCounter))
777       return false;
778 
779     LLVM_DEBUG({
780       dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n";
781       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
782     });
783     Constant *TrueC =
784         ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType()));
785     Cmp->replaceUsesWithIf(TrueC, [](Use &U) {
786       // Conditions in an assume trivially simplify to true. Skip uses
787       // in assume calls to not destroy the available information.
788       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
789       return !II || II->getIntrinsicID() != Intrinsic::assume;
790     });
791     NumCondsRemoved++;
792     Changed = true;
793   }
794   if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) {
795     if (!DebugCounter::shouldExecute(EliminatedCounter))
796       return false;
797 
798     LLVM_DEBUG({
799       dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n";
800       dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
801     });
802     Constant *FalseC =
803         ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType()));
804     Cmp->replaceAllUsesWith(FalseC);
805     NumCondsRemoved++;
806     Changed = true;
807   }
808   return Changed;
809 }
810 
811 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
812                              unsigned NumIn, unsigned NumOut,
813                              SmallVectorImpl<StackEntry> &DFSInStack) {
814   // If the constraint has a pre-condition, skip the constraint if it does not
815   // hold.
816   SmallVector<Value *> NewVariables;
817   auto R = getConstraint(Pred, A, B, NewVariables);
818   if (!R.isValid(*this))
819     return;
820 
821   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
822              A->printAsOperand(dbgs(), false); dbgs() << ", ";
823              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
824   bool Added = false;
825   auto &CSToUse = getCS(R.IsSigned);
826   if (R.Coefficients.empty())
827     return;
828 
829   Added |= CSToUse.addVariableRowFill(R.Coefficients);
830 
831   // If R has been added to the system, add the new variables and queue it for
832   // removal once it goes out-of-scope.
833   if (Added) {
834     SmallVector<Value *, 2> ValuesToRelease;
835     auto &Value2Index = getValue2Index(R.IsSigned);
836     for (Value *V : NewVariables) {
837       Value2Index.insert({V, Value2Index.size() + 1});
838       ValuesToRelease.push_back(V);
839     }
840 
841     LLVM_DEBUG({
842       dbgs() << "  constraint: ";
843       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
844       dbgs() << "\n";
845     });
846 
847     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
848                             std::move(ValuesToRelease));
849 
850     if (R.IsEq) {
851       // Also add the inverted constraint for equality constraints.
852       for (auto &Coeff : R.Coefficients)
853         Coeff *= -1;
854       CSToUse.addVariableRowFill(R.Coefficients);
855 
856       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
857                               SmallVector<Value *, 2>());
858     }
859   }
860 }
861 
862 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
863                                    SmallVectorImpl<Instruction *> &ToRemove) {
864   bool Changed = false;
865   IRBuilder<> Builder(II->getParent(), II->getIterator());
866   Value *Sub = nullptr;
867   for (User *U : make_early_inc_range(II->users())) {
868     if (match(U, m_ExtractValue<0>(m_Value()))) {
869       if (!Sub)
870         Sub = Builder.CreateSub(A, B);
871       U->replaceAllUsesWith(Sub);
872       Changed = true;
873     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
874       U->replaceAllUsesWith(Builder.getFalse());
875       Changed = true;
876     } else
877       continue;
878 
879     if (U->use_empty()) {
880       auto *I = cast<Instruction>(U);
881       ToRemove.push_back(I);
882       I->setOperand(0, PoisonValue::get(II->getType()));
883       Changed = true;
884     }
885   }
886 
887   if (II->use_empty()) {
888     II->eraseFromParent();
889     Changed = true;
890   }
891   return Changed;
892 }
893 
894 static bool
895 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
896                           SmallVectorImpl<Instruction *> &ToRemove) {
897   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
898                               ConstraintInfo &Info) {
899     auto R = Info.getConstraintForSolving(Pred, A, B);
900     if (R.size() < 2 || !R.isValid(Info))
901       return false;
902 
903     auto &CSToUse = Info.getCS(R.IsSigned);
904     return CSToUse.isConditionImplied(R.Coefficients);
905   };
906 
907   bool Changed = false;
908   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
909     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
910     // can be simplified to a regular sub.
911     Value *A = II->getArgOperand(0);
912     Value *B = II->getArgOperand(1);
913     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
914         !DoesConditionHold(CmpInst::ICMP_SGE, B,
915                            ConstantInt::get(A->getType(), 0), Info))
916       return false;
917     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
918   }
919   return Changed;
920 }
921 
922 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
923   bool Changed = false;
924   DT.updateDFSNumbers();
925 
926   ConstraintInfo Info(F.getParent()->getDataLayout());
927   State S(DT);
928 
929   // First, collect conditions implied by branches and blocks with their
930   // Dominator DFS in and out numbers.
931   for (BasicBlock &BB : F) {
932     if (!DT.getNode(&BB))
933       continue;
934     S.addInfoFor(BB);
935   }
936 
937   // Next, sort worklist by dominance, so that dominating conditions to check
938   // and facts come before conditions and facts dominated by them. If a
939   // condition to check and a fact have the same numbers, conditional facts come
940   // first. Assume facts and checks are ordered according to their relative
941   // order in the containing basic block. Also make sure conditions with
942   // constant operands come before conditions without constant operands. This
943   // increases the effectiveness of the current signed <-> unsigned fact
944   // transfer logic.
945   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
946     auto HasNoConstOp = [](const FactOrCheck &B) {
947       return !isa<ConstantInt>(B.Inst->getOperand(0)) &&
948              !isa<ConstantInt>(B.Inst->getOperand(1));
949     };
950     // If both entries have the same In numbers, conditional facts come first.
951     // Otherwise use the relative order in the basic block.
952     if (A.NumIn == B.NumIn) {
953       if (A.isConditionFact() && B.isConditionFact()) {
954         bool NoConstOpA = HasNoConstOp(A);
955         bool NoConstOpB = HasNoConstOp(B);
956         return NoConstOpA < NoConstOpB;
957       }
958       if (A.isConditionFact())
959         return true;
960       if (B.isConditionFact())
961         return false;
962       return A.Inst->comesBefore(B.Inst);
963     }
964     return A.NumIn < B.NumIn;
965   });
966 
967   SmallVector<Instruction *> ToRemove;
968 
969   // Finally, process ordered worklist and eliminate implied conditions.
970   SmallVector<StackEntry, 16> DFSInStack;
971   for (FactOrCheck &CB : S.WorkList) {
972     // First, pop entries from the stack that are out-of-scope for CB. Remove
973     // the corresponding entry from the constraint system.
974     while (!DFSInStack.empty()) {
975       auto &E = DFSInStack.back();
976       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
977                         << "\n");
978       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
979       assert(E.NumIn <= CB.NumIn);
980       if (CB.NumOut <= E.NumOut)
981         break;
982       LLVM_DEBUG({
983         dbgs() << "Removing ";
984         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
985                       Info.getValue2Index(E.IsSigned));
986         dbgs() << "\n";
987       });
988 
989       Info.popLastConstraint(E.IsSigned);
990       // Remove variables in the system that went out of scope.
991       auto &Mapping = Info.getValue2Index(E.IsSigned);
992       for (Value *V : E.ValuesToRelease)
993         Mapping.erase(V);
994       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
995       DFSInStack.pop_back();
996     }
997 
998     LLVM_DEBUG({
999       dbgs() << "Processing ";
1000       if (CB.IsCheck)
1001         dbgs() << "condition to simplify: " << *CB.Inst;
1002       else
1003         dbgs() << "fact to add to the system: " << *CB.Inst;
1004       dbgs() << "\n";
1005     });
1006 
1007     // For a block, check if any CmpInsts become known based on the current set
1008     // of constraints.
1009     if (CB.IsCheck) {
1010       if (auto *II = dyn_cast<WithOverflowInst>(CB.Inst)) {
1011         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1012       } else if (auto *Cmp = dyn_cast<ICmpInst>(CB.Inst)) {
1013         Changed |= checkAndReplaceCondition(Cmp, Info);
1014       }
1015       continue;
1016     }
1017 
1018     ICmpInst::Predicate Pred;
1019     Value *A, *B;
1020     Value *Cmp = CB.Inst;
1021     match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp)));
1022     if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1023       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1024         LLVM_DEBUG(
1025             dbgs()
1026             << "Skip adding constraint because system has too many rows.\n");
1027         continue;
1028       }
1029 
1030       // Use the inverse predicate if required.
1031       if (CB.Not)
1032         Pred = CmpInst::getInversePredicate(Pred);
1033 
1034       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1035       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1036     }
1037   }
1038 
1039 #ifndef NDEBUG
1040   unsigned SignedEntries =
1041       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1042   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1043          "updates to CS and DFSInStack are out of sync");
1044   assert(Info.getCS(true).size() == SignedEntries &&
1045          "updates to CS and DFSInStack are out of sync");
1046 #endif
1047 
1048   for (Instruction *I : ToRemove)
1049     I->eraseFromParent();
1050   return Changed;
1051 }
1052 
1053 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1054                                                  FunctionAnalysisManager &AM) {
1055   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1056   if (!eliminateConstraints(F, DT))
1057     return PreservedAnalyses::all();
1058 
1059   PreservedAnalyses PA;
1060   PA.preserve<DominatorTreeAnalysis>();
1061   PA.preserveSet<CFGAnalyses>();
1062   return PA;
1063 }
1064