LLVM  16.0.0git
InstructionSimplify.cpp
Go to the documentation of this file.
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
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 routines for folding instructions into simpler forms
10 // that do not require creating new instructions. This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18 
20 
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
35 #include "llvm/IR/ConstantRange.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/PatternMatch.h"
42 #include "llvm/Support/KnownBits.h"
43 #include <algorithm>
44 #include <optional>
45 using namespace llvm;
46 using namespace llvm::PatternMatch;
47 
48 #define DEBUG_TYPE "instsimplify"
49 
50 enum { RecursionLimit = 3 };
51 
52 STATISTIC(NumExpand, "Number of expansions");
53 STATISTIC(NumReassoc, "Number of reassociations");
54 
55 static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
56  unsigned);
57 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
58 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
59  const SimplifyQuery &, unsigned);
60 static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
61  unsigned);
62 static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
63  const SimplifyQuery &, unsigned);
64 static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
65  unsigned);
66 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
67  const SimplifyQuery &Q, unsigned MaxRecurse);
68 static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
69 static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
70  unsigned);
71 static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
72  unsigned);
74  const SimplifyQuery &, unsigned);
75 static Value *simplifySelectInst(Value *, Value *, Value *,
76  const SimplifyQuery &, unsigned);
77 
79  Value *FalseVal) {
80  BinaryOperator::BinaryOps BinOpCode;
81  if (auto *BO = dyn_cast<BinaryOperator>(Cond))
82  BinOpCode = BO->getOpcode();
83  else
84  return nullptr;
85 
86  CmpInst::Predicate ExpectedPred, Pred1, Pred2;
87  if (BinOpCode == BinaryOperator::Or) {
88  ExpectedPred = ICmpInst::ICMP_NE;
89  } else if (BinOpCode == BinaryOperator::And) {
90  ExpectedPred = ICmpInst::ICMP_EQ;
91  } else
92  return nullptr;
93 
94  // %A = icmp eq %TV, %FV
95  // %B = icmp eq %X, %Y (and one of these is a select operand)
96  // %C = and %A, %B
97  // %D = select %C, %TV, %FV
98  // -->
99  // %FV
100 
101  // %A = icmp ne %TV, %FV
102  // %B = icmp ne %X, %Y (and one of these is a select operand)
103  // %C = or %A, %B
104  // %D = select %C, %TV, %FV
105  // -->
106  // %TV
107  Value *X, *Y;
110  m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
111  Pred1 != Pred2 || Pred1 != ExpectedPred)
112  return nullptr;
113 
114  if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
115  return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
116 
117  return nullptr;
118 }
119 
120 /// For a boolean type or a vector of boolean type, return false or a vector
121 /// with every element false.
122 static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
123 
124 /// For a boolean type or a vector of boolean type, return true or a vector
125 /// with every element true.
126 static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
127 
128 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
130  Value *RHS) {
131  CmpInst *Cmp = dyn_cast<CmpInst>(V);
132  if (!Cmp)
133  return false;
134  CmpInst::Predicate CPred = Cmp->getPredicate();
135  Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
136  if (CPred == Pred && CLHS == LHS && CRHS == RHS)
137  return true;
138  return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
139  CRHS == LHS;
140 }
141 
142 /// Simplify comparison with true or false branch of select:
143 /// %sel = select i1 %cond, i32 %tv, i32 %fv
144 /// %cmp = icmp sle i32 %sel, %rhs
145 /// Compose new comparison by substituting %sel with either %tv or %fv
146 /// and see if it simplifies.
148  Value *RHS, Value *Cond,
149  const SimplifyQuery &Q, unsigned MaxRecurse,
150  Constant *TrueOrFalse) {
151  Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
152  if (SimplifiedCmp == Cond) {
153  // %cmp simplified to the select condition (%cond).
154  return TrueOrFalse;
155  } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
156  // It didn't simplify. However, if composed comparison is equivalent
157  // to the select condition (%cond) then we can replace it.
158  return TrueOrFalse;
159  }
160  return SimplifiedCmp;
161 }
162 
163 /// Simplify comparison with true branch of select
165  Value *RHS, Value *Cond,
166  const SimplifyQuery &Q,
167  unsigned MaxRecurse) {
168  return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
169  getTrue(Cond->getType()));
170 }
171 
172 /// Simplify comparison with false branch of select
174  Value *RHS, Value *Cond,
175  const SimplifyQuery &Q,
176  unsigned MaxRecurse) {
177  return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
178  getFalse(Cond->getType()));
179 }
180 
181 /// We know comparison with both branches of select can be simplified, but they
182 /// are not equal. This routine handles some logical simplifications.
184  Value *Cond,
185  const SimplifyQuery &Q,
186  unsigned MaxRecurse) {
187  // If the false value simplified to false, then the result of the compare
188  // is equal to "Cond && TCmp". This also catches the case when the false
189  // value simplified to false and the true value to true, returning "Cond".
190  // Folding select to and/or isn't poison-safe in general; impliesPoison
191  // checks whether folding it does not convert a well-defined value into
192  // poison.
193  if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
194  if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
195  return V;
196  // If the true value simplified to true, then the result of the compare
197  // is equal to "Cond || FCmp".
198  if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
199  if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
200  return V;
201  // Finally, if the false value simplified to true and the true value to
202  // false, then the result of the compare is equal to "!Cond".
203  if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
204  if (Value *V = simplifyXorInst(
205  Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
206  return V;
207  return nullptr;
208 }
209 
210 /// Does the given value dominate the specified phi node?
211 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
212  Instruction *I = dyn_cast<Instruction>(V);
213  if (!I)
214  // Arguments and constants dominate all instructions.
215  return true;
216 
217  // If we are processing instructions (and/or basic blocks) that have not been
218  // fully added to a function, the parent nodes may still be null. Simply
219  // return the conservative answer in these cases.
220  if (!I->getParent() || !P->getParent() || !I->getFunction())
221  return false;
222 
223  // If we have a DominatorTree then do a precise test.
224  if (DT)
225  return DT->dominates(I, P);
226 
227  // Otherwise, if the instruction is in the entry block and is not an invoke,
228  // then it obviously dominates all phi nodes.
229  if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
230  !isa<CallBrInst>(I))
231  return true;
232 
233  return false;
234 }
235 
236 /// Try to simplify a binary operator of form "V op OtherOp" where V is
237 /// "(B0 opex B1)" by distributing 'op' across 'opex' as
238 /// "(B0 op OtherOp) opex (B1 op OtherOp)".
240  Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
241  const SimplifyQuery &Q, unsigned MaxRecurse) {
242  auto *B = dyn_cast<BinaryOperator>(V);
243  if (!B || B->getOpcode() != OpcodeToExpand)
244  return nullptr;
245  Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
246  Value *L =
247  simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
248  if (!L)
249  return nullptr;
250  Value *R =
251  simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
252  if (!R)
253  return nullptr;
254 
255  // Does the expanded pair of binops simplify to the existing binop?
256  if ((L == B0 && R == B1) ||
257  (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
258  ++NumExpand;
259  return B;
260  }
261 
262  // Otherwise, return "L op' R" if it simplifies.
263  Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
264  if (!S)
265  return nullptr;
266 
267  ++NumExpand;
268  return S;
269 }
270 
271 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
272 /// distributing op over op'.
274  Value *R,
275  Instruction::BinaryOps OpcodeToExpand,
276  const SimplifyQuery &Q,
277  unsigned MaxRecurse) {
278  // Recursion is always used, so bail out at once if we already hit the limit.
279  if (!MaxRecurse--)
280  return nullptr;
281 
282  if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
283  return V;
284  if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
285  return V;
286  return nullptr;
287 }
288 
289 /// Generic simplifications for associative binary operations.
290 /// Returns the simpler value, or null if none was found.
292  Value *LHS, Value *RHS,
293  const SimplifyQuery &Q,
294  unsigned MaxRecurse) {
295  assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
296 
297  // Recursion is always used, so bail out at once if we already hit the limit.
298  if (!MaxRecurse--)
299  return nullptr;
300 
301  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
302  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
303 
304  // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
305  if (Op0 && Op0->getOpcode() == Opcode) {
306  Value *A = Op0->getOperand(0);
307  Value *B = Op0->getOperand(1);
308  Value *C = RHS;
309 
310  // Does "B op C" simplify?
311  if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
312  // It does! Return "A op V" if it simplifies or is already available.
313  // If V equals B then "A op V" is just the LHS.
314  if (V == B)
315  return LHS;
316  // Otherwise return "A op V" if it simplifies.
317  if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
318  ++NumReassoc;
319  return W;
320  }
321  }
322  }
323 
324  // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
325  if (Op1 && Op1->getOpcode() == Opcode) {
326  Value *A = LHS;
327  Value *B = Op1->getOperand(0);
328  Value *C = Op1->getOperand(1);
329 
330  // Does "A op B" simplify?
331  if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
332  // It does! Return "V op C" if it simplifies or is already available.
333  // If V equals B then "V op C" is just the RHS.
334  if (V == B)
335  return RHS;
336  // Otherwise return "V op C" if it simplifies.
337  if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
338  ++NumReassoc;
339  return W;
340  }
341  }
342  }
343 
344  // The remaining transforms require commutativity as well as associativity.
345  if (!Instruction::isCommutative(Opcode))
346  return nullptr;
347 
348  // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
349  if (Op0 && Op0->getOpcode() == Opcode) {
350  Value *A = Op0->getOperand(0);
351  Value *B = Op0->getOperand(1);
352  Value *C = RHS;
353 
354  // Does "C op A" simplify?
355  if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
356  // It does! Return "V op B" if it simplifies or is already available.
357  // If V equals A then "V op B" is just the LHS.
358  if (V == A)
359  return LHS;
360  // Otherwise return "V op B" if it simplifies.
361  if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
362  ++NumReassoc;
363  return W;
364  }
365  }
366  }
367 
368  // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
369  if (Op1 && Op1->getOpcode() == Opcode) {
370  Value *A = LHS;
371  Value *B = Op1->getOperand(0);
372  Value *C = Op1->getOperand(1);
373 
374  // Does "C op A" simplify?
375  if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
376  // It does! Return "B op V" if it simplifies or is already available.
377  // If V equals C then "B op V" is just the RHS.
378  if (V == C)
379  return RHS;
380  // Otherwise return "B op V" if it simplifies.
381  if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
382  ++NumReassoc;
383  return W;
384  }
385  }
386  }
387 
388  return nullptr;
389 }
390 
391 /// In the case of a binary operation with a select instruction as an operand,
392 /// try to simplify the binop by seeing whether evaluating it on both branches
393 /// of the select results in the same value. Returns the common value if so,
394 /// otherwise returns null.
396  Value *RHS, const SimplifyQuery &Q,
397  unsigned MaxRecurse) {
398  // Recursion is always used, so bail out at once if we already hit the limit.
399  if (!MaxRecurse--)
400  return nullptr;
401 
402  SelectInst *SI;
403  if (isa<SelectInst>(LHS)) {
404  SI = cast<SelectInst>(LHS);
405  } else {
406  assert(isa<SelectInst>(RHS) && "No select instruction operand!");
407  SI = cast<SelectInst>(RHS);
408  }
409 
410  // Evaluate the BinOp on the true and false branches of the select.
411  Value *TV;
412  Value *FV;
413  if (SI == LHS) {
414  TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
415  FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
416  } else {
417  TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
418  FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
419  }
420 
421  // If they simplified to the same value, then return the common value.
422  // If they both failed to simplify then return null.
423  if (TV == FV)
424  return TV;
425 
426  // If one branch simplified to undef, return the other one.
427  if (TV && Q.isUndefValue(TV))
428  return FV;
429  if (FV && Q.isUndefValue(FV))
430  return TV;
431 
432  // If applying the operation did not change the true and false select values,
433  // then the result of the binop is the select itself.
434  if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
435  return SI;
436 
437  // If one branch simplified and the other did not, and the simplified
438  // value is equal to the unsimplified one, return the simplified value.
439  // For example, select (cond, X, X & Z) & Z -> X & Z.
440  if ((FV && !TV) || (TV && !FV)) {
441  // Check that the simplified value has the form "X op Y" where "op" is the
442  // same as the original operation.
443  Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
444  if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
445  // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
446  // We already know that "op" is the same as for the simplified value. See
447  // if the operands match too. If so, return the simplified value.
448  Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
449  Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
450  Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
451  if (Simplified->getOperand(0) == UnsimplifiedLHS &&
452  Simplified->getOperand(1) == UnsimplifiedRHS)
453  return Simplified;
454  if (Simplified->isCommutative() &&
455  Simplified->getOperand(1) == UnsimplifiedLHS &&
456  Simplified->getOperand(0) == UnsimplifiedRHS)
457  return Simplified;
458  }
459  }
460 
461  return nullptr;
462 }
463 
464 /// In the case of a comparison with a select instruction, try to simplify the
465 /// comparison by seeing whether both branches of the select result in the same
466 /// value. Returns the common value if so, otherwise returns null.
467 /// For example, if we have:
468 /// %tmp = select i1 %cmp, i32 1, i32 2
469 /// %cmp1 = icmp sle i32 %tmp, 3
470 /// We can simplify %cmp1 to true, because both branches of select are
471 /// less than 3. We compose new comparison by substituting %tmp with both
472 /// branches of select and see if it can be simplified.
474  Value *RHS, const SimplifyQuery &Q,
475  unsigned MaxRecurse) {
476  // Recursion is always used, so bail out at once if we already hit the limit.
477  if (!MaxRecurse--)
478  return nullptr;
479 
480  // Make sure the select is on the LHS.
481  if (!isa<SelectInst>(LHS)) {
482  std::swap(LHS, RHS);
483  Pred = CmpInst::getSwappedPredicate(Pred);
484  }
485  assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
486  SelectInst *SI = cast<SelectInst>(LHS);
487  Value *Cond = SI->getCondition();
488  Value *TV = SI->getTrueValue();
489  Value *FV = SI->getFalseValue();
490 
491  // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
492  // Does "cmp TV, RHS" simplify?
493  Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
494  if (!TCmp)
495  return nullptr;
496 
497  // Does "cmp FV, RHS" simplify?
498  Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
499  if (!FCmp)
500  return nullptr;
501 
502  // If both sides simplified to the same value, then use it as the result of
503  // the original comparison.
504  if (TCmp == FCmp)
505  return TCmp;
506 
507  // The remaining cases only make sense if the select condition has the same
508  // type as the result of the comparison, so bail out if this is not so.
509  if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
510  return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
511 
512  return nullptr;
513 }
514 
515 /// In the case of a binary operation with an operand that is a PHI instruction,
516 /// try to simplify the binop by seeing whether evaluating it on the incoming
517 /// phi values yields the same result for every value. If so returns the common
518 /// value, otherwise returns null.
520  Value *RHS, const SimplifyQuery &Q,
521  unsigned MaxRecurse) {
522  // Recursion is always used, so bail out at once if we already hit the limit.
523  if (!MaxRecurse--)
524  return nullptr;
525 
526  PHINode *PI;
527  if (isa<PHINode>(LHS)) {
528  PI = cast<PHINode>(LHS);
529  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
530  if (!valueDominatesPHI(RHS, PI, Q.DT))
531  return nullptr;
532  } else {
533  assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
534  PI = cast<PHINode>(RHS);
535  // Bail out if LHS and the phi may be mutually interdependent due to a loop.
536  if (!valueDominatesPHI(LHS, PI, Q.DT))
537  return nullptr;
538  }
539 
540  // Evaluate the BinOp on the incoming phi values.
541  Value *CommonValue = nullptr;
542  for (Value *Incoming : PI->incoming_values()) {
543  // If the incoming value is the phi node itself, it can safely be skipped.
544  if (Incoming == PI)
545  continue;
546  Value *V = PI == LHS ? simplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse)
547  : simplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
548  // If the operation failed to simplify, or simplified to a different value
549  // to previously, then give up.
550  if (!V || (CommonValue && V != CommonValue))
551  return nullptr;
552  CommonValue = V;
553  }
554 
555  return CommonValue;
556 }
557 
558 /// In the case of a comparison with a PHI instruction, try to simplify the
559 /// comparison by seeing whether comparing with all of the incoming phi values
560 /// yields the same result every time. If so returns the common result,
561 /// otherwise returns null.
563  const SimplifyQuery &Q, unsigned MaxRecurse) {
564  // Recursion is always used, so bail out at once if we already hit the limit.
565  if (!MaxRecurse--)
566  return nullptr;
567 
568  // Make sure the phi is on the LHS.
569  if (!isa<PHINode>(LHS)) {
570  std::swap(LHS, RHS);
571  Pred = CmpInst::getSwappedPredicate(Pred);
572  }
573  assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
574  PHINode *PI = cast<PHINode>(LHS);
575 
576  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
577  if (!valueDominatesPHI(RHS, PI, Q.DT))
578  return nullptr;
579 
580  // Evaluate the BinOp on the incoming phi values.
581  Value *CommonValue = nullptr;
582  for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
583  Value *Incoming = PI->getIncomingValue(u);
584  Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
585  // If the incoming value is the phi node itself, it can safely be skipped.
586  if (Incoming == PI)
587  continue;
588  // Change the context instruction to the "edge" that flows into the phi.
589  // This is important because that is where incoming is actually "evaluated"
590  // even though it is used later somewhere else.
591  Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
592  MaxRecurse);
593  // If the operation failed to simplify, or simplified to a different value
594  // to previously, then give up.
595  if (!V || (CommonValue && V != CommonValue))
596  return nullptr;
597  CommonValue = V;
598  }
599 
600  return CommonValue;
601 }
602 
604  Value *&Op0, Value *&Op1,
605  const SimplifyQuery &Q) {
606  if (auto *CLHS = dyn_cast<Constant>(Op0)) {
607  if (auto *CRHS = dyn_cast<Constant>(Op1)) {
608  switch (Opcode) {
609  default:
610  break;
611  case Instruction::FAdd:
612  case Instruction::FSub:
613  case Instruction::FMul:
614  case Instruction::FDiv:
615  case Instruction::FRem:
616  if (Q.CxtI != nullptr)
617  return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
618  }
619  return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
620  }
621 
622  // Canonicalize the constant to the RHS if this is a commutative operation.
623  if (Instruction::isCommutative(Opcode))
624  std::swap(Op0, Op1);
625  }
626  return nullptr;
627 }
628 
629 /// Given operands for an Add, see if we can fold the result.
630 /// If not, this returns null.
631 static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
632  const SimplifyQuery &Q, unsigned MaxRecurse) {
633  if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
634  return C;
635 
636  // X + poison -> poison
637  if (isa<PoisonValue>(Op1))
638  return Op1;
639 
640  // X + undef -> undef
641  if (Q.isUndefValue(Op1))
642  return Op1;
643 
644  // X + 0 -> X
645  if (match(Op1, m_Zero()))
646  return Op0;
647 
648  // If two operands are negative, return 0.
649  if (isKnownNegation(Op0, Op1))
650  return Constant::getNullValue(Op0->getType());
651 
652  // X + (Y - X) -> Y
653  // (Y - X) + X -> Y
654  // Eg: X + -X -> 0
655  Value *Y = nullptr;
656  if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
657  match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
658  return Y;
659 
660  // X + ~X -> -1 since ~X = -X-1
661  Type *Ty = Op0->getType();
662  if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
663  return Constant::getAllOnesValue(Ty);
664 
665  // add nsw/nuw (xor Y, signmask), signmask --> Y
666  // The no-wrapping add guarantees that the top bit will be set by the add.
667  // Therefore, the xor must be clearing the already set sign bit of Y.
668  if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
669  match(Op0, m_Xor(m_Value(Y), m_SignMask())))
670  return Y;
671 
672  // add nuw %x, -1 -> -1, because %x can only be 0.
673  if (IsNUW && match(Op1, m_AllOnes()))
674  return Op1; // Which is -1.
675 
676  /// i1 add -> xor.
677  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
678  if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
679  return V;
680 
681  // Try some generic simplifications for associative operations.
682  if (Value *V =
683  simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
684  return V;
685 
686  // Threading Add over selects and phi nodes is pointless, so don't bother.
687  // Threading over the select in "A + select(cond, B, C)" means evaluating
688  // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
689  // only if B and C are equal. If B and C are equal then (since we assume
690  // that operands have already been simplified) "select(cond, B, C)" should
691  // have been simplified to the common value of B and C already. Analysing
692  // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
693  // for threading over phi nodes.
694 
695  return nullptr;
696 }
697 
698 Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
699  const SimplifyQuery &Query) {
700  return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
701 }
702 
703 /// Compute the base pointer and cumulative constant offsets for V.
704 ///
705 /// This strips all constant offsets off of V, leaving it the base pointer, and
706 /// accumulates the total constant offset applied in the returned constant.
707 /// It returns zero if there are no constant offsets applied.
708 ///
709 /// This is very similar to stripAndAccumulateConstantOffsets(), except it
710 /// normalizes the offset bitwidth to the stripped pointer type, not the
711 /// original pointer type.
713  bool AllowNonInbounds = false) {
715 
716  APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
717  V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
718  // As that strip may trace through `addrspacecast`, need to sext or trunc
719  // the offset calculated.
720  return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
721 }
722 
723 /// Compute the constant difference between two pointer values.
724 /// If the difference is not a constant, returns zero.
726  Value *RHS) {
729 
730  // If LHS and RHS are not related via constant offsets to the same base
731  // value, there is nothing we can do here.
732  if (LHS != RHS)
733  return nullptr;
734 
735  // Otherwise, the difference of LHS - RHS can be computed as:
736  // LHS - RHS
737  // = (LHSOffset + Base) - (RHSOffset + Base)
738  // = LHSOffset - RHSOffset
739  Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
740  if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
741  Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
742  return Res;
743 }
744 
745 /// Test if there is a dominating equivalence condition for the
746 /// two operands. If there is, try to reduce the binary operation
747 /// between the two operands.
748 /// Example: Op0 - Op1 --> 0 when Op0 == Op1
749 static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
750  const SimplifyQuery &Q, unsigned MaxRecurse) {
751  // Recursive run it can not get any benefit
752  if (MaxRecurse != RecursionLimit)
753  return nullptr;
754 
755  Optional<bool> Imp =
757  if (Imp && *Imp) {
758  Type *Ty = Op0->getType();
759  switch (Opcode) {
760  case Instruction::Sub:
761  case Instruction::Xor:
762  case Instruction::URem:
763  case Instruction::SRem:
764  return Constant::getNullValue(Ty);
765 
766  case Instruction::SDiv:
767  case Instruction::UDiv:
768  return ConstantInt::get(Ty, 1);
769 
770  case Instruction::And:
771  case Instruction::Or:
772  // Could be either one - choose Op1 since that's more likely a constant.
773  return Op1;
774  default:
775  break;
776  }
777  }
778  return nullptr;
779 }
780 
781 /// Given operands for a Sub, see if we can fold the result.
782 /// If not, this returns null.
783 static Value *simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
784  const SimplifyQuery &Q, unsigned MaxRecurse) {
785  if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
786  return C;
787 
788  // X - poison -> poison
789  // poison - X -> poison
790  if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
791  return PoisonValue::get(Op0->getType());
792 
793  // X - undef -> undef
794  // undef - X -> undef
795  if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
796  return UndefValue::get(Op0->getType());
797 
798  // X - 0 -> X
799  if (match(Op1, m_Zero()))
800  return Op0;
801 
802  // X - X -> 0
803  if (Op0 == Op1)
804  return Constant::getNullValue(Op0->getType());
805 
806  // Is this a negation?
807  if (match(Op0, m_Zero())) {
808  // 0 - X -> 0 if the sub is NUW.
809  if (isNUW)
810  return Constant::getNullValue(Op0->getType());
811 
812  KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
813  if (Known.Zero.isMaxSignedValue()) {
814  // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
815  // Op1 must be 0 because negating the minimum signed value is undefined.
816  if (isNSW)
817  return Constant::getNullValue(Op0->getType());
818 
819  // 0 - X -> X if X is 0 or the minimum signed value.
820  return Op1;
821  }
822  }
823 
824  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
825  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
826  Value *X = nullptr, *Y = nullptr, *Z = Op1;
827  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
828  // See if "V === Y - Z" simplifies.
829  if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
830  // It does! Now see if "X + V" simplifies.
831  if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
832  // It does, we successfully reassociated!
833  ++NumReassoc;
834  return W;
835  }
836  // See if "V === X - Z" simplifies.
837  if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
838  // It does! Now see if "Y + V" simplifies.
839  if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
840  // It does, we successfully reassociated!
841  ++NumReassoc;
842  return W;
843  }
844  }
845 
846  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
847  // For example, X - (X + 1) -> -1
848  X = Op0;
849  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
850  // See if "V === X - Y" simplifies.
851  if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
852  // It does! Now see if "V - Z" simplifies.
853  if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
854  // It does, we successfully reassociated!
855  ++NumReassoc;
856  return W;
857  }
858  // See if "V === X - Z" simplifies.
859  if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
860  // It does! Now see if "V - Y" simplifies.
861  if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
862  // It does, we successfully reassociated!
863  ++NumReassoc;
864  return W;
865  }
866  }
867 
868  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
869  // For example, X - (X - Y) -> Y.
870  Z = Op0;
871  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
872  // See if "V === Z - X" simplifies.
873  if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
874  // It does! Now see if "V + Y" simplifies.
875  if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
876  // It does, we successfully reassociated!
877  ++NumReassoc;
878  return W;
879  }
880 
881  // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
882  if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
883  match(Op1, m_Trunc(m_Value(Y))))
884  if (X->getType() == Y->getType())
885  // See if "V === X - Y" simplifies.
886  if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
887  // It does! Now see if "trunc V" simplifies.
888  if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
889  Q, MaxRecurse - 1))
890  // It does, return the simplified "trunc V".
891  return W;
892 
893  // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
894  if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
895  if (Constant *Result = computePointerDifference(Q.DL, X, Y))
896  return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
897 
898  // i1 sub -> xor.
899  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
900  if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
901  return V;
902 
903  // Threading Sub over selects and phi nodes is pointless, so don't bother.
904  // Threading over the select in "A - select(cond, B, C)" means evaluating
905  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
906  // only if B and C are equal. If B and C are equal then (since we assume
907  // that operands have already been simplified) "select(cond, B, C)" should
908  // have been simplified to the common value of B and C already. Analysing
909  // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
910  // for threading over phi nodes.
911 
912  if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
913  return V;
914 
915  return nullptr;
916 }
917 
918 Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
919  const SimplifyQuery &Q) {
920  return ::simplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
921 }
922 
923 /// Given operands for a Mul, see if we can fold the result.
924 /// If not, this returns null.
925 static Value *simplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
926  unsigned MaxRecurse) {
927  if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
928  return C;
929 
930  // X * poison -> poison
931  if (isa<PoisonValue>(Op1))
932  return Op1;
933 
934  // X * undef -> 0
935  // X * 0 -> 0
936  if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
937  return Constant::getNullValue(Op0->getType());
938 
939  // X * 1 -> X
940  if (match(Op1, m_One()))
941  return Op0;
942 
943  // (X / Y) * Y -> X if the division is exact.
944  Value *X = nullptr;
945  if (Q.IIQ.UseInstrInfo &&
946  (match(Op0,
947  m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
948  match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
949  return X;
950 
951  // i1 mul -> and.
952  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
953  if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
954  return V;
955 
956  // Try some generic simplifications for associative operations.
957  if (Value *V =
958  simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
959  return V;
960 
961  // Mul distributes over Add. Try some generic simplifications based on this.
962  if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
963  Instruction::Add, Q, MaxRecurse))
964  return V;
965 
966  // If the operation is with the result of a select instruction, check whether
967  // operating on either branch of the select always yields the same value.
968  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
969  if (Value *V =
970  threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
971  return V;
972 
973  // If the operation is with the result of a phi instruction, check whether
974  // operating on all incoming values of the phi always yields the same value.
975  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
976  if (Value *V =
977  threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
978  return V;
979 
980  return nullptr;
981 }
982 
985 }
986 
987 /// Check for common or similar folds of integer division or integer remainder.
988 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
990  Value *Op1, const SimplifyQuery &Q,
991  unsigned MaxRecurse) {
992  bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
993  bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
994 
995  Type *Ty = Op0->getType();
996 
997  // X / undef -> poison
998  // X % undef -> poison
999  if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
1000  return PoisonValue::get(Ty);
1001 
1002  // X / 0 -> poison
1003  // X % 0 -> poison
1004  // We don't need to preserve faults!
1005  if (match(Op1, m_Zero()))
1006  return PoisonValue::get(Ty);
1007 
1008  // If any element of a constant divisor fixed width vector is zero or undef
1009  // the behavior is undefined and we can fold the whole op to poison.
1010  auto *Op1C = dyn_cast<Constant>(Op1);
1011  auto *VTy = dyn_cast<FixedVectorType>(Ty);
1012  if (Op1C && VTy) {
1013  unsigned NumElts = VTy->getNumElements();
1014  for (unsigned i = 0; i != NumElts; ++i) {
1015  Constant *Elt = Op1C->getAggregateElement(i);
1016  if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
1017  return PoisonValue::get(Ty);
1018  }
1019  }
1020 
1021  // poison / X -> poison
1022  // poison % X -> poison
1023  if (isa<PoisonValue>(Op0))
1024  return Op0;
1025 
1026  // undef / X -> 0
1027  // undef % X -> 0
1028  if (Q.isUndefValue(Op0))
1029  return Constant::getNullValue(Ty);
1030 
1031  // 0 / X -> 0
1032  // 0 % X -> 0
1033  if (match(Op0, m_Zero()))
1034  return Constant::getNullValue(Op0->getType());
1035 
1036  // X / X -> 1
1037  // X % X -> 0
1038  if (Op0 == Op1)
1039  return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1040 
1041  // X / 1 -> X
1042  // X % 1 -> 0
1043  // If this is a boolean op (single-bit element type), we can't have
1044  // division-by-zero or remainder-by-zero, so assume the divisor is 1.
1045  // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
1046  Value *X;
1047  if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
1048  (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1049  return IsDiv ? Op0 : Constant::getNullValue(Ty);
1050 
1051  // If X * Y does not overflow, then:
1052  // X * Y / Y -> X
1053  // X * Y % Y -> 0
1054  if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1055  auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1056  // The multiplication can't overflow if it is defined not to, or if
1057  // X == A / Y for some A.
1058  if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1059  (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1060  (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1061  (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1062  return IsDiv ? X : Constant::getNullValue(Op0->getType());
1063  }
1064  }
1065 
1066  if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1067  return V;
1068 
1069  return nullptr;
1070 }
1071 
1072 /// Given a predicate and two operands, return true if the comparison is true.
1073 /// This is a helper for div/rem simplification where we return some other value
1074 /// when we can prove a relationship between the operands.
1076  const SimplifyQuery &Q, unsigned MaxRecurse) {
1077  Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
1078  Constant *C = dyn_cast_or_null<Constant>(V);
1079  return (C && C->isAllOnesValue());
1080 }
1081 
1082 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
1083 /// to simplify X % Y to X.
1084 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
1085  unsigned MaxRecurse, bool IsSigned) {
1086  // Recursion is always used, so bail out at once if we already hit the limit.
1087  if (!MaxRecurse--)
1088  return false;
1089 
1090  if (IsSigned) {
1091  // |X| / |Y| --> 0
1092  //
1093  // We require that 1 operand is a simple constant. That could be extended to
1094  // 2 variables if we computed the sign bit for each.
1095  //
1096  // Make sure that a constant is not the minimum signed value because taking
1097  // the abs() of that is undefined.
1098  Type *Ty = X->getType();
1099  const APInt *C;
1100  if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1101  // Is the variable divisor magnitude always greater than the constant
1102  // dividend magnitude?
1103  // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1104  Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1105  Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1106  if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1107  isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1108  return true;
1109  }
1110  if (match(Y, m_APInt(C))) {
1111  // Special-case: we can't take the abs() of a minimum signed value. If
1112  // that's the divisor, then all we have to do is prove that the dividend
1113  // is also not the minimum signed value.
1114  if (C->isMinSignedValue())
1115  return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1116 
1117  // Is the variable dividend magnitude always less than the constant
1118  // divisor magnitude?
1119  // |X| < |C| --> X > -abs(C) and X < abs(C)
1120  Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1121  Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1122  if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1123  isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1124  return true;
1125  }
1126  return false;
1127  }
1128 
1129  // IsSigned == false.
1130 
1131  // Is the unsigned dividend known to be less than a constant divisor?
1132  // TODO: Convert this (and above) to range analysis
1133  // ("computeConstantRangeIncludingKnownBits")?
1134  const APInt *C;
1135  if (match(Y, m_APInt(C)) &&
1136  computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
1137  return true;
1138 
1139  // Try again for any divisor:
1140  // Is the dividend unsigned less than the divisor?
1141  return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1142 }
1143 
1144 /// These are simplifications common to SDiv and UDiv.
1146  const SimplifyQuery &Q, unsigned MaxRecurse) {
1147  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1148  return C;
1149 
1150  if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1151  return V;
1152 
1153  bool IsSigned = Opcode == Instruction::SDiv;
1154 
1155  // (X rem Y) / Y -> 0
1156  if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1157  (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1158  return Constant::getNullValue(Op0->getType());
1159 
1160  // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1161  ConstantInt *C1, *C2;
1162  if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
1163  match(Op1, m_ConstantInt(C2))) {
1164  bool Overflow;
1165  (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1166  if (Overflow)
1167  return Constant::getNullValue(Op0->getType());
1168  }
1169 
1170  // If the operation is with the result of a select instruction, check whether
1171  // operating on either branch of the select always yields the same value.
1172  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1173  if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1174  return V;
1175 
1176  // If the operation is with the result of a phi instruction, check whether
1177  // operating on all incoming values of the phi always yields the same value.
1178  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1179  if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1180  return V;
1181 
1182  if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1183  return Constant::getNullValue(Op0->getType());
1184 
1185  return nullptr;
1186 }
1187 
1188 /// These are simplifications common to SRem and URem.
1190  const SimplifyQuery &Q, unsigned MaxRecurse) {
1191  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1192  return C;
1193 
1194  if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1195  return V;
1196 
1197  // (X % Y) % Y -> X % Y
1198  if ((Opcode == Instruction::SRem &&
1199  match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1200  (Opcode == Instruction::URem &&
1201  match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1202  return Op0;
1203 
1204  // (X << Y) % X -> 0
1205  if (Q.IIQ.UseInstrInfo &&
1206  ((Opcode == Instruction::SRem &&
1207  match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1208  (Opcode == Instruction::URem &&
1209  match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1210  return Constant::getNullValue(Op0->getType());
1211 
1212  // If the operation is with the result of a select instruction, check whether
1213  // operating on either branch of the select always yields the same value.
1214  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1215  if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1216  return V;
1217 
1218  // If the operation is with the result of a phi instruction, check whether
1219  // operating on all incoming values of the phi always yields the same value.
1220  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1221  if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1222  return V;
1223 
1224  // If X / Y == 0, then X % Y == X.
1225  if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1226  return Op0;
1227 
1228  return nullptr;
1229 }
1230 
1231 /// Given operands for an SDiv, see if we can fold the result.
1232 /// If not, this returns null.
1233 static Value *simplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1234  unsigned MaxRecurse) {
1235  // If two operands are negated and no signed overflow, return -1.
1236  if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1237  return Constant::getAllOnesValue(Op0->getType());
1238 
1239  return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1240 }
1241 
1244 }
1245 
1246 /// Given operands for a UDiv, see if we can fold the result.
1247 /// If not, this returns null.
1248 static Value *simplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1249  unsigned MaxRecurse) {
1250  return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1251 }
1252 
1255 }
1256 
1257 /// Given operands for an SRem, see if we can fold the result.
1258 /// If not, this returns null.
1259 static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1260  unsigned MaxRecurse) {
1261  // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1262  // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1263  Value *X;
1264  if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1265  return ConstantInt::getNullValue(Op0->getType());
1266 
1267  // If the two operands are negated, return 0.
1268  if (isKnownNegation(Op0, Op1))
1269  return ConstantInt::getNullValue(Op0->getType());
1270 
1271  return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1272 }
1273 
1276 }
1277 
1278 /// Given operands for a URem, see if we can fold the result.
1279 /// If not, this returns null.
1280 static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1281  unsigned MaxRecurse) {
1282  return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1283 }
1284 
1287 }
1288 
1289 /// Returns true if a shift by \c Amount always yields poison.
1290 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1291  Constant *C = dyn_cast<Constant>(Amount);
1292  if (!C)
1293  return false;
1294 
1295  // X shift by undef -> poison because it may shift by the bitwidth.
1296  if (Q.isUndefValue(C))
1297  return true;
1298 
1299  // Shifting by the bitwidth or more is poison. This covers scalars and
1300  // fixed/scalable vectors with splat constants.
1301  const APInt *AmountC;
1302  if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
1303  return true;
1304 
1305  // Try harder for fixed-length vectors:
1306  // If all lanes of a vector shift are poison, the whole shift is poison.
1307  if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1308  for (unsigned I = 0,
1309  E = cast<FixedVectorType>(C->getType())->getNumElements();
1310  I != E; ++I)
1311  if (!isPoisonShift(C->getAggregateElement(I), Q))
1312  return false;
1313  return true;
1314  }
1315 
1316  return false;
1317 }
1318 
1319 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1320 /// If not, this returns null.
1322  Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1323  unsigned MaxRecurse) {
1324  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1325  return C;
1326 
1327  // poison shift by X -> poison
1328  if (isa<PoisonValue>(Op0))
1329  return Op0;
1330 
1331  // 0 shift by X -> 0
1332  if (match(Op0, m_Zero()))
1333  return Constant::getNullValue(Op0->getType());
1334 
1335  // X shift by 0 -> X
1336  // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1337  // would be poison.
1338  Value *X;
1339  if (match(Op1, m_Zero()) ||
1340  (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1341  return Op0;
1342 
1343  // Fold undefined shifts.
1344  if (isPoisonShift(Op1, Q))
1345  return PoisonValue::get(Op0->getType());
1346 
1347  // If the operation is with the result of a select instruction, check whether
1348  // operating on either branch of the select always yields the same value.
1349  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1350  if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1351  return V;
1352 
1353  // If the operation is with the result of a phi instruction, check whether
1354  // operating on all incoming values of the phi always yields the same value.
1355  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1356  if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1357  return V;
1358 
1359  // If any bits in the shift amount make that value greater than or equal to
1360  // the number of bits in the type, the shift is undefined.
1361  KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1362  if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1363  return PoisonValue::get(Op0->getType());
1364 
1365  // If all valid bits in the shift amount are known zero, the first operand is
1366  // unchanged.
1367  unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1368  if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1369  return Op0;
1370 
1371  // Check for nsw shl leading to a poison value.
1372  if (IsNSW) {
1373  assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1374  KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1375  KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1376 
1377  if (KnownVal.Zero.isSignBitSet())
1378  KnownShl.Zero.setSignBit();
1379  if (KnownVal.One.isSignBitSet())
1380  KnownShl.One.setSignBit();
1381 
1382  if (KnownShl.hasConflict())
1383  return PoisonValue::get(Op0->getType());
1384  }
1385 
1386  return nullptr;
1387 }
1388 
1389 /// Given operands for an Shl, LShr or AShr, see if we can
1390 /// fold the result. If not, this returns null.
1392  Value *Op1, bool isExact,
1393  const SimplifyQuery &Q, unsigned MaxRecurse) {
1394  if (Value *V =
1395  simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1396  return V;
1397 
1398  // X >> X -> 0
1399  if (Op0 == Op1)
1400  return Constant::getNullValue(Op0->getType());
1401 
1402  // undef >> X -> 0
1403  // undef >> X -> undef (if it's exact)
1404  if (Q.isUndefValue(Op0))
1405  return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1406 
1407  // The low bit cannot be shifted out of an exact shift if it is set.
1408  if (isExact) {
1409  KnownBits Op0Known =
1410  computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1411  if (Op0Known.One[0])
1412  return Op0;
1413  }
1414 
1415  return nullptr;
1416 }
1417 
1418 /// Given operands for an Shl, see if we can fold the result.
1419 /// If not, this returns null.
1420 static Value *simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1421  const SimplifyQuery &Q, unsigned MaxRecurse) {
1422  if (Value *V =
1423  simplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse))
1424  return V;
1425 
1426  // undef << X -> 0
1427  // undef << X -> undef if (if it's NSW/NUW)
1428  if (Q.isUndefValue(Op0))
1429  return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1430 
1431  // (X >> A) << A -> X
1432  Value *X;
1433  if (Q.IIQ.UseInstrInfo &&
1434  match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1435  return X;
1436 
1437  // shl nuw i8 C, %x -> C iff C has sign bit set.
1438  if (isNUW && match(Op0, m_Negative()))
1439  return Op0;
1440  // NOTE: could use computeKnownBits() / LazyValueInfo,
1441  // but the cost-benefit analysis suggests it isn't worth it.
1442 
1443  return nullptr;
1444 }
1445 
1446 Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1447  const SimplifyQuery &Q) {
1448  return ::simplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1449 }
1450 
1451 /// Given operands for an LShr, see if we can fold the result.
1452 /// If not, this returns null.
1453 static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1454  const SimplifyQuery &Q, unsigned MaxRecurse) {
1455  if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1456  MaxRecurse))
1457  return V;
1458 
1459  // (X << A) >> A -> X
1460  Value *X;
1461  if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1462  return X;
1463 
1464  // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1465  // We can return X as we do in the above case since OR alters no bits in X.
1466  // SimplifyDemandedBits in InstCombine can do more general optimization for
1467  // bit manipulation. This pattern aims to provide opportunities for other
1468  // optimizers by supporting a simple but common case in InstSimplify.
1469  Value *Y;
1470  const APInt *ShRAmt, *ShLAmt;
1471  if (match(Op1, m_APInt(ShRAmt)) &&
1472  match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1473  *ShRAmt == *ShLAmt) {
1474  const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1475  const unsigned EffWidthY = YKnown.countMaxActiveBits();
1476  if (ShRAmt->uge(EffWidthY))
1477  return X;
1478  }
1479 
1480  return nullptr;
1481 }
1482 
1483 Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1484  const SimplifyQuery &Q) {
1485  return ::simplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1486 }
1487 
1488 /// Given operands for an AShr, see if we can fold the result.
1489 /// If not, this returns null.
1490 static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1491  const SimplifyQuery &Q, unsigned MaxRecurse) {
1492  if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1493  MaxRecurse))
1494  return V;
1495 
1496  // -1 >>a X --> -1
1497  // (-1 << X) a>> X --> -1
1498  // Do not return Op0 because it may contain undef elements if it's a vector.
1499  if (match(Op0, m_AllOnes()) ||
1500  match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1501  return Constant::getAllOnesValue(Op0->getType());
1502 
1503  // (X << A) >> A -> X
1504  Value *X;
1505  if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1506  return X;
1507 
1508  // Arithmetic shifting an all-sign-bit value is a no-op.
1509  unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1510  if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1511  return Op0;
1512 
1513  return nullptr;
1514 }
1515 
1516 Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1517  const SimplifyQuery &Q) {
1518  return ::simplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1519 }
1520 
1521 /// Commuted variants are assumed to be handled by calling this function again
1522 /// with the parameters swapped.
1524  ICmpInst *UnsignedICmp, bool IsAnd,
1525  const SimplifyQuery &Q) {
1526  Value *X, *Y;
1527 
1528  ICmpInst::Predicate EqPred;
1529  if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1530  !ICmpInst::isEquality(EqPred))
1531  return nullptr;
1532 
1533  ICmpInst::Predicate UnsignedPred;
1534 
1535  Value *A, *B;
1536  // Y = (A - B);
1537  if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1538  if (match(UnsignedICmp,
1539  m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1540  ICmpInst::isUnsigned(UnsignedPred)) {
1541  // A >=/<= B || (A - B) != 0 <--> true
1542  if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1543  UnsignedPred == ICmpInst::ICMP_ULE) &&
1544  EqPred == ICmpInst::ICMP_NE && !IsAnd)
1545  return ConstantInt::getTrue(UnsignedICmp->getType());
1546  // A </> B && (A - B) == 0 <--> false
1547  if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1548  UnsignedPred == ICmpInst::ICMP_UGT) &&
1549  EqPred == ICmpInst::ICMP_EQ && IsAnd)
1550  return ConstantInt::getFalse(UnsignedICmp->getType());
1551 
1552  // A </> B && (A - B) != 0 <--> A </> B
1553  // A </> B || (A - B) != 0 <--> (A - B) != 0
1554  if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1555  UnsignedPred == ICmpInst::ICMP_UGT))
1556  return IsAnd ? UnsignedICmp : ZeroICmp;
1557 
1558  // A <=/>= B && (A - B) == 0 <--> (A - B) == 0
1559  // A <=/>= B || (A - B) == 0 <--> A <=/>= B
1560  if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1561  UnsignedPred == ICmpInst::ICMP_UGE))
1562  return IsAnd ? ZeroICmp : UnsignedICmp;
1563  }
1564 
1565  // Given Y = (A - B)
1566  // Y >= A && Y != 0 --> Y >= A iff B != 0
1567  // Y < A || Y == 0 --> Y < A iff B != 0
1568  if (match(UnsignedICmp,
1569  m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1570  if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1571  EqPred == ICmpInst::ICMP_NE &&
1572  isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1573  return UnsignedICmp;
1574  if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1575  EqPred == ICmpInst::ICMP_EQ &&
1576  isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1577  return UnsignedICmp;
1578  }
1579  }
1580 
1581  if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1582  ICmpInst::isUnsigned(UnsignedPred))
1583  ;
1584  else if (match(UnsignedICmp,
1585  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1586  ICmpInst::isUnsigned(UnsignedPred))
1587  UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1588  else
1589  return nullptr;
1590 
1591  // X > Y && Y == 0 --> Y == 0 iff X != 0
1592  // X > Y || Y == 0 --> X > Y iff X != 0
1593  if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1594  isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1595  return IsAnd ? ZeroICmp : UnsignedICmp;
1596 
1597  // X <= Y && Y != 0 --> X <= Y iff X != 0
1598  // X <= Y || Y != 0 --> Y != 0 iff X != 0
1599  if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1600  isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1601  return IsAnd ? UnsignedICmp : ZeroICmp;
1602 
1603  // The transforms below here are expected to be handled more generally with
1604  // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1605  // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1606  // these are candidates for removal.
1607 
1608  // X < Y && Y != 0 --> X < Y
1609  // X < Y || Y != 0 --> Y != 0
1610  if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1611  return IsAnd ? UnsignedICmp : ZeroICmp;
1612 
1613  // X >= Y && Y == 0 --> Y == 0
1614  // X >= Y || Y == 0 --> X >= Y
1615  if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1616  return IsAnd ? ZeroICmp : UnsignedICmp;
1617 
1618  // X < Y && Y == 0 --> false
1619  if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1620  IsAnd)
1621  return getFalse(UnsignedICmp->getType());
1622 
1623  // X >= Y || Y != 0 --> true
1624  if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1625  !IsAnd)
1626  return getTrue(UnsignedICmp->getType());
1627 
1628  return nullptr;
1629 }
1630 
1631 /// Test if a pair of compares with a shared operand and 2 constants has an
1632 /// empty set intersection, full set union, or if one compare is a superset of
1633 /// the other.
1635  bool IsAnd) {
1636  // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1637  if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1638  return nullptr;
1639 
1640  const APInt *C0, *C1;
1641  if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1642  !match(Cmp1->getOperand(1), m_APInt(C1)))
1643  return nullptr;
1644 
1645  auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1646  auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1647 
1648  // For and-of-compares, check if the intersection is empty:
1649  // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1650  if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1651  return getFalse(Cmp0->getType());
1652 
1653  // For or-of-compares, check if the union is full:
1654  // (icmp X, C0) || (icmp X, C1) --> full set --> true
1655  if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1656  return getTrue(Cmp0->getType());
1657 
1658  // Is one range a superset of the other?
1659  // If this is and-of-compares, take the smaller set:
1660  // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1661  // If this is or-of-compares, take the larger set:
1662  // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1663  if (Range0.contains(Range1))
1664  return IsAnd ? Cmp1 : Cmp0;
1665  if (Range1.contains(Range0))
1666  return IsAnd ? Cmp0 : Cmp1;
1667 
1668  return nullptr;
1669 }
1670 
1672  bool IsAnd) {
1673  ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1674  if (!match(Cmp0->getOperand(1), m_Zero()) ||
1675  !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1676  return nullptr;
1677 
1678  if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1679  return nullptr;
1680 
1681  // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1682  Value *X = Cmp0->getOperand(0);
1683  Value *Y = Cmp1->getOperand(0);
1684 
1685  // If one of the compares is a masked version of a (not) null check, then
1686  // that compare implies the other, so we eliminate the other. Optionally, look
1687  // through a pointer-to-int cast to match a null check of a pointer type.
1688 
1689  // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1690  // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1691  // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1692  // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1693  if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1695  return Cmp1;
1696 
1697  // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1698  // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1699  // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1700  // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1701  if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1703  return Cmp0;
1704 
1705  return nullptr;
1706 }
1707 
1709  const InstrInfoQuery &IIQ) {
1710  // (icmp (add V, C0), C1) & (icmp V, C0)
1711  ICmpInst::Predicate Pred0, Pred1;
1712  const APInt *C0, *C1;
1713  Value *V;
1714  if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1715  return nullptr;
1716 
1717  if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1718  return nullptr;
1719 
1720  auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1721  if (AddInst->getOperand(1) != Op1->getOperand(1))
1722  return nullptr;
1723 
1724  Type *ITy = Op0->getType();
1725  bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1726  bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1727 
1728  const APInt Delta = *C1 - *C0;
1729  if (C0->isStrictlyPositive()) {
1730  if (Delta == 2) {
1731  if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1732  return getFalse(ITy);
1733  if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1734  return getFalse(ITy);
1735  }
1736  if (Delta == 1) {
1737  if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1738  return getFalse(ITy);
1739  if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1740  return getFalse(ITy);
1741  }
1742  }
1743  if (C0->getBoolValue() && isNUW) {
1744  if (Delta == 2)
1745  if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1746  return getFalse(ITy);
1747  if (Delta == 1)
1748  if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1749  return getFalse(ITy);
1750  }
1751 
1752  return nullptr;
1753 }
1754 
1755 /// Try to eliminate compares with signed or unsigned min/max constants.
1757  bool IsAnd) {
1758  // Canonicalize an equality compare as Cmp0.
1759  if (Cmp1->isEquality())
1760  std::swap(Cmp0, Cmp1);
1761  if (!Cmp0->isEquality())
1762  return nullptr;
1763 
1764  // The non-equality compare must include a common operand (X). Canonicalize
1765  // the common operand as operand 0 (the predicate is swapped if the common
1766  // operand was operand 1).
1767  ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
1768  Value *X = Cmp0->getOperand(0);
1769  ICmpInst::Predicate Pred1;
1770  bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
1771  if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
1772  return nullptr;
1773  if (ICmpInst::isEquality(Pred1))
1774  return nullptr;
1775 
1776  // The equality compare must be against a constant. Flip bits if we matched
1777  // a bitwise not. Convert a null pointer constant to an integer zero value.
1778  APInt MinMaxC;
1779  const APInt *C;
1780  if (match(Cmp0->getOperand(1), m_APInt(C)))
1781  MinMaxC = HasNotOp ? ~*C : *C;
1782  else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
1783  MinMaxC = APInt::getZero(8);
1784  else
1785  return nullptr;
1786 
1787  // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
1788  if (!IsAnd) {
1789  Pred0 = ICmpInst::getInversePredicate(Pred0);
1790  Pred1 = ICmpInst::getInversePredicate(Pred1);
1791  }
1792 
1793  // Normalize to unsigned compare and unsigned min/max value.
1794  // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
1795  if (ICmpInst::isSigned(Pred1)) {
1796  Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
1797  MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
1798  }
1799 
1800  // (X != MAX) && (X < Y) --> X < Y
1801  // (X == MAX) || (X >= Y) --> X >= Y
1802  if (MinMaxC.isMaxValue())
1803  if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
1804  return Cmp1;
1805 
1806  // (X != MIN) && (X > Y) --> X > Y
1807  // (X == MIN) || (X <= Y) --> X <= Y
1808  if (MinMaxC.isMinValue())
1809  if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
1810  return Cmp1;
1811 
1812  return nullptr;
1813 }
1814 
1815 /// Try to simplify and/or of icmp with ctpop intrinsic.
1817  bool IsAnd) {
1818  ICmpInst::Predicate Pred0, Pred1;
1819  Value *X;
1820  const APInt *C;
1821  if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1822  m_APInt(C))) ||
1823  !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1824  return nullptr;
1825 
1826  // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1827  if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1828  return Cmp1;
1829  // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1830  if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1831  return Cmp1;
1832 
1833  return nullptr;
1834 }
1835 
1837  const SimplifyQuery &Q) {
1838  if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1839  return X;
1840  if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1841  return X;
1842 
1843  if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1844  return X;
1845 
1846  if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1847  return X;
1848 
1849  if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1850  return X;
1851 
1852  if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1853  return X;
1854  if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1855  return X;
1856 
1857  if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1858  return X;
1859  if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1860  return X;
1861 
1862  return nullptr;
1863 }
1864 
1866  const InstrInfoQuery &IIQ) {
1867  // (icmp (add V, C0), C1) | (icmp V, C0)
1868  ICmpInst::Predicate Pred0, Pred1;
1869  const APInt *C0, *C1;
1870  Value *V;
1871  if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1872  return nullptr;
1873 
1874  if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1875  return nullptr;
1876 
1877  auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1878  if (AddInst->getOperand(1) != Op1->getOperand(1))
1879  return nullptr;
1880 
1881  Type *ITy = Op0->getType();
1882  bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1883  bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1884 
1885  const APInt Delta = *C1 - *C0;
1886  if (C0->isStrictlyPositive()) {
1887  if (Delta == 2) {
1888  if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1889  return getTrue(ITy);
1890  if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1891  return getTrue(ITy);
1892  }
1893  if (Delta == 1) {
1894  if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1895  return getTrue(ITy);
1896  if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1897  return getTrue(ITy);
1898  }
1899  }
1900  if (C0->getBoolValue() && isNUW) {
1901  if (Delta == 2)
1902  if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1903  return getTrue(ITy);
1904  if (Delta == 1)
1905  if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1906  return getTrue(ITy);
1907  }
1908 
1909  return nullptr;
1910 }
1911 
1913  const SimplifyQuery &Q) {
1914  if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1915  return X;
1916  if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1917  return X;
1918 
1919  if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1920  return X;
1921 
1922  if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1923  return X;
1924 
1925  if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1926  return X;
1927 
1928  if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1929  return X;
1930  if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1931  return X;
1932 
1933  if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1934  return X;
1935  if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1936  return X;
1937 
1938  return nullptr;
1939 }
1940 
1942  FCmpInst *RHS, bool IsAnd) {
1943  Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1944  Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1945  if (LHS0->getType() != RHS0->getType())
1946  return nullptr;
1947 
1948  FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1949  if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1950  (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1951  // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1952  // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1953  // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1954  // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1955  // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1956  // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1957  // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1958  // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1959  if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1960  (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1961  return RHS;
1962 
1963  // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1964  // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1965  // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1966  // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1967  // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1968  // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1969  // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1970  // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1971  if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1972  (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1973  return LHS;
1974  }
1975 
1976  return nullptr;
1977 }
1978 
1980  Value *Op1, bool IsAnd) {
1981  // Look through casts of the 'and' operands to find compares.
1982  auto *Cast0 = dyn_cast<CastInst>(Op0);
1983  auto *Cast1 = dyn_cast<CastInst>(Op1);
1984  if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1985  Cast0->getSrcTy() == Cast1->getSrcTy()) {
1986  Op0 = Cast0->getOperand(0);
1987  Op1 = Cast1->getOperand(0);
1988  }
1989 
1990  Value *V = nullptr;
1991  auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1992  auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1993  if (ICmp0 && ICmp1)
1994  V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1995  : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1996 
1997  auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1998  auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1999  if (FCmp0 && FCmp1)
2000  V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
2001 
2002  if (!V)
2003  return nullptr;
2004  if (!Cast0)
2005  return V;
2006 
2007  // If we looked through casts, we can only handle a constant simplification
2008  // because we are not allowed to create a cast instruction here.
2009  if (auto *C = dyn_cast<Constant>(V))
2010  return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
2011 
2012  return nullptr;
2013 }
2014 
2015 /// Given a bitwise logic op, check if the operands are add/sub with a common
2016 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
2018  Instruction::BinaryOps Opcode) {
2019  assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
2020  assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
2021  Value *X;
2022  Constant *C1, *C2;
2023  if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
2024  match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
2025  (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2026  match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2027  if (ConstantExpr::getNot(C1) == C2) {
2028  // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2029  // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2030  // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2031  Type *Ty = Op0->getType();
2032  return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2034  }
2035  }
2036  return nullptr;
2037 }
2038 
2039 /// Given operands for an And, see if we can fold the result.
2040 /// If not, this returns null.
2041 static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2042  unsigned MaxRecurse) {
2043  if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2044  return C;
2045 
2046  // X & poison -> poison
2047  if (isa<PoisonValue>(Op1))
2048  return Op1;
2049 
2050  // X & undef -> 0
2051  if (Q.isUndefValue(Op1))
2052  return Constant::getNullValue(Op0->getType());
2053 
2054  // X & X = X
2055  if (Op0 == Op1)
2056  return Op0;
2057 
2058  // X & 0 = 0
2059  if (match(Op1, m_Zero()))
2060  return Constant::getNullValue(Op0->getType());
2061 
2062  // X & -1 = X
2063  if (match(Op1, m_AllOnes()))
2064  return Op0;
2065 
2066  // A & ~A = ~A & A = 0
2067  if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2068  return Constant::getNullValue(Op0->getType());
2069 
2070  // (A | ?) & A = A
2071  if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2072  return Op1;
2073 
2074  // A & (A | ?) = A
2075  if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
2076  return Op0;
2077 
2078  // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2079  Value *X, *Y;
2080  if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2081  match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2082  return X;
2083  if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2084  match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2085  return X;
2086 
2087  if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2088  return V;
2089 
2090  // A mask that only clears known zeros of a shifted value is a no-op.
2091  const APInt *Mask;
2092  const APInt *ShAmt;
2093  if (match(Op1, m_APInt(Mask))) {
2094  // If all bits in the inverted and shifted mask are clear:
2095  // and (shl X, ShAmt), Mask --> shl X, ShAmt
2096  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2097  (~(*Mask)).lshr(*ShAmt).isZero())
2098  return Op0;
2099 
2100  // If all bits in the inverted and shifted mask are clear:
2101  // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2102  if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2103  (~(*Mask)).shl(*ShAmt).isZero())
2104  return Op0;
2105  }
2106 
2107  // If we have a multiplication overflow check that is being 'and'ed with a
2108  // check that one of the multipliers is not zero, we can omit the 'and', and
2109  // only keep the overflow check.
2110  if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2111  return Op1;
2112  if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
2113  return Op0;
2114 
2115  // A & (-A) = A if A is a power of two or zero.
2116  if (match(Op0, m_Neg(m_Specific(Op1))) ||
2117  match(Op1, m_Neg(m_Specific(Op0)))) {
2118  if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2119  Q.DT))
2120  return Op0;
2121  if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2122  Q.DT))
2123  return Op1;
2124  }
2125 
2126  // This is a similar pattern used for checking if a value is a power-of-2:
2127  // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2128  // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
2129  if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2130  isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2131  return Constant::getNullValue(Op1->getType());
2132  if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
2133  isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2134  return Constant::getNullValue(Op0->getType());
2135 
2136  if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2137  return V;
2138 
2139  // Try some generic simplifications for associative operations.
2140  if (Value *V =
2141  simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
2142  return V;
2143 
2144  // And distributes over Or. Try some generic simplifications based on this.
2145  if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2146  Instruction::Or, Q, MaxRecurse))
2147  return V;
2148 
2149  // And distributes over Xor. Try some generic simplifications based on this.
2150  if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2151  Instruction::Xor, Q, MaxRecurse))
2152  return V;
2153 
2154  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2155  if (Op0->getType()->isIntOrIntVectorTy(1)) {
2156  // A & (A && B) -> A && B
2157  if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2158  return Op1;
2159  else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2160  return Op0;
2161  }
2162  // If the operation is with the result of a select instruction, check
2163  // whether operating on either branch of the select always yields the same
2164  // value.
2165  if (Value *V =
2166  threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
2167  return V;
2168  }
2169 
2170  // If the operation is with the result of a phi instruction, check whether
2171  // operating on all incoming values of the phi always yields the same value.
2172  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2173  if (Value *V =
2174  threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
2175  return V;
2176 
2177  // Assuming the effective width of Y is not larger than A, i.e. all bits
2178  // from X and Y are disjoint in (X << A) | Y,
2179  // if the mask of this AND op covers all bits of X or Y, while it covers
2180  // no bits from the other, we can bypass this AND op. E.g.,
2181  // ((X << A) | Y) & Mask -> Y,
2182  // if Mask = ((1 << effective_width_of(Y)) - 1)
2183  // ((X << A) | Y) & Mask -> X << A,
2184  // if Mask = ((1 << effective_width_of(X)) - 1) << A
2185  // SimplifyDemandedBits in InstCombine can optimize the general case.
2186  // This pattern aims to help other passes for a common case.
2187  Value *XShifted;
2188  if (match(Op1, m_APInt(Mask)) &&
2190  m_Value(XShifted)),
2191  m_Value(Y)))) {
2192  const unsigned Width = Op0->getType()->getScalarSizeInBits();
2193  const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2194  const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2195  const unsigned EffWidthY = YKnown.countMaxActiveBits();
2196  if (EffWidthY <= ShftCnt) {
2197  const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2198  const unsigned EffWidthX = XKnown.countMaxActiveBits();
2199  const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2200  const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2201  // If the mask is extracting all bits from X or Y as is, we can skip
2202  // this AND op.
2203  if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2204  return Y;
2205  if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2206  return XShifted;
2207  }
2208  }
2209 
2210  // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2211  // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2212  BinaryOperator *Or;
2213  if (match(Op0, m_c_Xor(m_Value(X),
2215  m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2216  match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2217  return Constant::getNullValue(Op0->getType());
2218 
2219  if (Op0->getType()->isIntOrIntVectorTy(1)) {
2220  if (Optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
2221  // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2222  if (*Implied == true)
2223  return Op0;
2224  // If Op0 is true implies Op1 is false, then they are not true together.
2225  if (*Implied == false)
2226  return ConstantInt::getFalse(Op0->getType());
2227  }
2228  if (Optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
2229  // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2230  if (Implied.value())
2231  return Op1;
2232  // If Op1 is true implies Op0 is false, then they are not true together.
2233  if (!Implied.value())
2234  return ConstantInt::getFalse(Op1->getType());
2235  }
2236  }
2237 
2238  if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2239  return V;
2240 
2241  return nullptr;
2242 }
2243 
2246 }
2247 
2248 // TODO: Many of these folds could use LogicalAnd/LogicalOr.
2250  assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2251  Type *Ty = X->getType();
2252 
2253  // X | ~X --> -1
2254  if (match(Y, m_Not(m_Specific(X))))
2255  return ConstantInt::getAllOnesValue(Ty);
2256 
2257  // X | ~(X & ?) = -1
2258  if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2259  return ConstantInt::getAllOnesValue(Ty);
2260 
2261  // X | (X & ?) --> X
2262  if (match(Y, m_c_And(m_Specific(X), m_Value())))
2263  return X;
2264 
2265  Value *A, *B;
2266 
2267  // (A ^ B) | (A | B) --> A | B
2268  // (A ^ B) | (B | A) --> B | A
2269  if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2270  match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2271  return Y;
2272 
2273  // ~(A ^ B) | (A | B) --> -1
2274  // ~(A ^ B) | (B | A) --> -1
2275  if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2276  match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2277  return ConstantInt::getAllOnesValue(Ty);
2278 
2279  // (A & ~B) | (A ^ B) --> A ^ B
2280  // (~B & A) | (A ^ B) --> A ^ B
2281  // (A & ~B) | (B ^ A) --> B ^ A
2282  // (~B & A) | (B ^ A) --> B ^ A
2283  if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2285  return Y;
2286 
2287  // (~A ^ B) | (A & B) --> ~A ^ B
2288  // (B ^ ~A) | (A & B) --> B ^ ~A
2289  // (~A ^ B) | (B & A) --> ~A ^ B
2290  // (B ^ ~A) | (B & A) --> B ^ ~A
2291  if (match(X, m_c_Xor(m_NotForbidUndef(m_Value(A)), m_Value(B))) &&
2293  return X;
2294 
2295  // (~A | B) | (A ^ B) --> -1
2296  // (~A | B) | (B ^ A) --> -1
2297  // (B | ~A) | (A ^ B) --> -1
2298  // (B | ~A) | (B ^ A) --> -1
2299  if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2301  return ConstantInt::getAllOnesValue(Ty);
2302 
2303  // (~A & B) | ~(A | B) --> ~A
2304  // (~A & B) | ~(B | A) --> ~A
2305  // (B & ~A) | ~(A | B) --> ~A
2306  // (B & ~A) | ~(B | A) --> ~A
2307  Value *NotA;
2308  if (match(X,
2310  m_Value(B))) &&
2312  return NotA;
2313  // The same is true of Logical And
2314  // TODO: This could share the logic of the version above if there was a
2315  // version of LogicalAnd that allowed more than just i1 types.
2316  if (match(X, m_c_LogicalAnd(
2318  m_Value(B))) &&
2320  return NotA;
2321 
2322  // ~(A ^ B) | (A & B) --> ~(A ^ B)
2323  // ~(A ^ B) | (B & A) --> ~(A ^ B)
2324  Value *NotAB;
2326  m_Value(NotAB))) &&
2328  return NotAB;
2329 
2330  // ~(A & B) | (A ^ B) --> ~(A & B)
2331  // ~(A & B) | (B ^ A) --> ~(A & B)
2333  m_Value(NotAB))) &&
2335  return NotAB;
2336 
2337  return nullptr;
2338 }
2339 
2340 /// Given operands for an Or, see if we can fold the result.
2341 /// If not, this returns null.
2342 static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2343  unsigned MaxRecurse) {
2344  if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2345  return C;
2346 
2347  // X | poison -> poison
2348  if (isa<PoisonValue>(Op1))
2349  return Op1;
2350 
2351  // X | undef -> -1
2352  // X | -1 = -1
2353  // Do not return Op1 because it may contain undef elements if it's a vector.
2354  if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2355  return Constant::getAllOnesValue(Op0->getType());
2356 
2357  // X | X = X
2358  // X | 0 = X
2359  if (Op0 == Op1 || match(Op1, m_Zero()))
2360  return Op0;
2361 
2362  if (Value *R = simplifyOrLogic(Op0, Op1))
2363  return R;
2364  if (Value *R = simplifyOrLogic(Op1, Op0))
2365  return R;
2366 
2367  if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2368  return V;
2369 
2370  // Rotated -1 is still -1:
2371  // (-1 << X) | (-1 >> (C - X)) --> -1
2372  // (-1 >> X) | (-1 << (C - X)) --> -1
2373  // ...with C <= bitwidth (and commuted variants).
2374  Value *X, *Y;
2375  if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2376  match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2377  (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2378  match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2379  const APInt *C;
2380  if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2381  match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2382  C->ule(X->getType()->getScalarSizeInBits())) {
2383  return ConstantInt::getAllOnesValue(X->getType());
2384  }
2385  }
2386 
2387  // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2388  // are mixing in another shift that is redundant with the funnel shift.
2389 
2390  // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2391  // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2392  if (match(Op0,
2393  m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2394  match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2395  return Op0;
2396  if (match(Op1,
2397  m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2398  match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2399  return Op1;
2400 
2401  // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2402  // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2403  if (match(Op0,
2404  m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2405  match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2406  return Op0;
2407  if (match(Op1,
2408  m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2409  match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2410  return Op1;
2411 
2412  if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2413  return V;
2414 
2415  // If we have a multiplication overflow check that is being 'and'ed with a
2416  // check that one of the multipliers is not zero, we can omit the 'and', and
2417  // only keep the overflow check.
2418  if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2419  return Op1;
2420  if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2421  return Op0;
2422 
2423  // Try some generic simplifications for associative operations.
2424  if (Value *V =
2425  simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2426  return V;
2427 
2428  // Or distributes over And. Try some generic simplifications based on this.
2429  if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2430  Instruction::And, Q, MaxRecurse))
2431  return V;
2432 
2433  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2434  if (Op0->getType()->isIntOrIntVectorTy(1)) {
2435  // A | (A || B) -> A || B
2436  if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2437  return Op1;
2438  else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2439  return Op0;
2440  }
2441  // If the operation is with the result of a select instruction, check
2442  // whether operating on either branch of the select always yields the same
2443  // value.
2444  if (Value *V =
2445  threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2446  return V;
2447  }
2448 
2449  // (A & C1)|(B & C2)
2450  Value *A, *B;
2451  const APInt *C1, *C2;
2452  if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2453  match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2454  if (*C1 == ~*C2) {
2455  // (A & C1)|(B & C2)
2456  // If we have: ((V + N) & C1) | (V & C2)
2457  // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2458  // replace with V+N.
2459  Value *N;
2460  if (C2->isMask() && // C2 == 0+1+
2461  match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2462  // Add commutes, try both ways.
2463  if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2464  return A;
2465  }
2466  // Or commutes, try both ways.
2467  if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2468  // Add commutes, try both ways.
2469  if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2470  return B;
2471  }
2472  }
2473  }
2474 
2475  // If the operation is with the result of a phi instruction, check whether
2476  // operating on all incoming values of the phi always yields the same value.
2477  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2478  if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2479  return V;
2480 
2481  if (Op0->getType()->isIntOrIntVectorTy(1)) {
2482  if (Optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL, false)) {
2483  // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2484  if (*Implied == false)
2485  return Op0;
2486  // If Op0 is false implies Op1 is true, then at least one is always true.
2487  if (*Implied == true)
2488  return ConstantInt::getTrue(Op0->getType());
2489  }
2490  if (Optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL, false)) {
2491  // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2492  if (*Implied == false)
2493  return Op1;
2494  // If Op1 is false implies Op0 is true, then at least one is always true.
2495  if (*Implied == true)
2496  return ConstantInt::getTrue(Op1->getType());
2497  }
2498  }
2499 
2500  if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2501  return V;
2502 
2503  return nullptr;
2504 }
2505 
2508 }
2509 
2510 /// Given operands for a Xor, see if we can fold the result.
2511 /// If not, this returns null.
2512 static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2513  unsigned MaxRecurse) {
2514  if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2515  return C;
2516 
2517  // X ^ poison -> poison
2518  if (isa<PoisonValue>(Op1))
2519  return Op1;
2520 
2521  // A ^ undef -> undef
2522  if (Q.isUndefValue(Op1))
2523  return Op1;
2524 
2525  // A ^ 0 = A
2526  if (match(Op1, m_Zero()))
2527  return Op0;
2528 
2529  // A ^ A = 0
2530  if (Op0 == Op1)
2531  return Constant::getNullValue(Op0->getType());
2532 
2533  // A ^ ~A = ~A ^ A = -1
2534  if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2535  return Constant::getAllOnesValue(Op0->getType());
2536 
2537  auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2538  Value *A, *B;
2539  // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2540  if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2541  match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2542  return A;
2543 
2544  // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2545  // The 'not' op must contain a complete -1 operand (no undef elements for
2546  // vector) for the transform to be safe.
2547  Value *NotA;
2548  if (match(X,
2550  m_Value(B))) &&
2552  return NotA;
2553 
2554  return nullptr;
2555  };
2556  if (Value *R = foldAndOrNot(Op0, Op1))
2557  return R;
2558  if (Value *R = foldAndOrNot(Op1, Op0))
2559  return R;
2560 
2561  if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2562  return V;
2563 
2564  // Try some generic simplifications for associative operations.
2565  if (Value *V =
2566  simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2567  return V;
2568 
2569  // Threading Xor over selects and phi nodes is pointless, so don't bother.
2570  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2571  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2572  // only if B and C are equal. If B and C are equal then (since we assume
2573  // that operands have already been simplified) "select(cond, B, C)" should
2574  // have been simplified to the common value of B and C already. Analysing
2575  // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2576  // for threading over phi nodes.
2577 
2578  if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2579  return V;
2580 
2581  return nullptr;
2582 }
2583 
2586 }
2587 
2589  return CmpInst::makeCmpResultType(Op->getType());
2590 }
2591 
2592 /// Rummage around inside V looking for something equivalent to the comparison
2593 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2594 /// Helper function for analyzing max/min idioms.
2596  Value *LHS, Value *RHS) {
2597  SelectInst *SI = dyn_cast<SelectInst>(V);
2598  if (!SI)
2599  return nullptr;
2600  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2601  if (!Cmp)
2602  return nullptr;
2603  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2604  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2605  return Cmp;
2606  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2607  LHS == CmpRHS && RHS == CmpLHS)
2608  return Cmp;
2609  return nullptr;
2610 }
2611 
2612 /// Return true if the underlying object (storage) must be disjoint from
2613 /// storage returned by any noalias return call.
2614 static bool isAllocDisjoint(const Value *V) {
2615  // For allocas, we consider only static ones (dynamic
2616  // allocas might be transformed into calls to malloc not simultaneously
2617  // live with the compared-to allocation). For globals, we exclude symbols
2618  // that might be resolve lazily to symbols in another dynamically-loaded
2619  // library (and, thus, could be malloc'ed by the implementation).
2620  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2621  return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2622  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2623  return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2624  GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2625  !GV->isThreadLocal();
2626  if (const Argument *A = dyn_cast<Argument>(V))
2627  return A->hasByValAttr();
2628  return false;
2629 }
2630 
2631 /// Return true if V1 and V2 are each the base of some distict storage region
2632 /// [V, object_size(V)] which do not overlap. Note that zero sized regions
2633 /// *are* possible, and that zero sized regions do not overlap with any other.
2634 static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2635  // Global variables always exist, so they always exist during the lifetime
2636  // of each other and all allocas. Global variables themselves usually have
2637  // non-overlapping storage, but since their addresses are constants, the
2638  // case involving two globals does not reach here and is instead handled in
2639  // constant folding.
2640  //
2641  // Two different allocas usually have different addresses...
2642  //
2643  // However, if there's an @llvm.stackrestore dynamically in between two
2644  // allocas, they may have the same address. It's tempting to reduce the
2645  // scope of the problem by only looking at *static* allocas here. That would
2646  // cover the majority of allocas while significantly reducing the likelihood
2647  // of having an @llvm.stackrestore pop up in the middle. However, it's not
2648  // actually impossible for an @llvm.stackrestore to pop up in the middle of
2649  // an entry block. Also, if we have a block that's not attached to a
2650  // function, we can't tell if it's "static" under the current definition.
2651  // Theoretically, this problem could be fixed by creating a new kind of
2652  // instruction kind specifically for static allocas. Such a new instruction
2653  // could be required to be at the top of the entry block, thus preventing it
2654  // from being subject to a @llvm.stackrestore. Instcombine could even
2655  // convert regular allocas into these special allocas. It'd be nifty.
2656  // However, until then, this problem remains open.
2657  //
2658  // So, we'll assume that two non-empty allocas have different addresses
2659  // for now.
2660  auto isByValArg = [](const Value *V) {
2661  const Argument *A = dyn_cast<Argument>(V);
2662  return A && A->hasByValAttr();
2663  };
2664 
2665  // Byval args are backed by store which does not overlap with each other,
2666  // allocas, or globals.
2667  if (isByValArg(V1))
2668  return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2669  if (isByValArg(V2))
2670  return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2671 
2672  return isa<AllocaInst>(V1) &&
2673  (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2674 }
2675 
2676 // A significant optimization not implemented here is assuming that alloca
2677 // addresses are not equal to incoming argument values. They don't *alias*,
2678 // as we say, but that doesn't mean they aren't equal, so we take a
2679 // conservative approach.
2680 //
2681 // This is inspired in part by C++11 5.10p1:
2682 // "Two pointers of the same type compare equal if and only if they are both
2683 // null, both point to the same function, or both represent the same
2684 // address."
2685 //
2686 // This is pretty permissive.
2687 //
2688 // It's also partly due to C11 6.5.9p6:
2689 // "Two pointers compare equal if and only if both are null pointers, both are
2690 // pointers to the same object (including a pointer to an object and a
2691 // subobject at its beginning) or function, both are pointers to one past the
2692 // last element of the same array object, or one is a pointer to one past the
2693 // end of one array object and the other is a pointer to the start of a
2694 // different array object that happens to immediately follow the first array
2695 // object in the address space.)
2696 //
2697 // C11's version is more restrictive, however there's no reason why an argument
2698 // couldn't be a one-past-the-end value for a stack object in the caller and be
2699 // equal to the beginning of a stack object in the callee.
2700 //
2701 // If the C and C++ standards are ever made sufficiently restrictive in this
2702 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2703 // this optimization.
2705  Value *RHS, const SimplifyQuery &Q) {
2706  const DataLayout &DL = Q.DL;
2707  const TargetLibraryInfo *TLI = Q.TLI;
2708  const DominatorTree *DT = Q.DT;
2709  const Instruction *CxtI = Q.CxtI;
2710  const InstrInfoQuery &IIQ = Q.IIQ;
2711 
2712  // First, skip past any trivial no-ops.
2713  LHS = LHS->stripPointerCasts();
2714  RHS = RHS->stripPointerCasts();
2715 
2716  // A non-null pointer is not equal to a null pointer.
2717  if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2718  llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2719  IIQ.UseInstrInfo))
2721 
2722  // We can only fold certain predicates on pointer comparisons.
2723  switch (Pred) {
2724  default:
2725  return nullptr;
2726 
2727  // Equality comparisons are easy to fold.
2728  case CmpInst::ICMP_EQ:
2729  case CmpInst::ICMP_NE:
2730  break;
2731 
2732  // We can only handle unsigned relational comparisons because 'inbounds' on
2733  // a GEP only protects against unsigned wrapping.
2734  case CmpInst::ICMP_UGT:
2735  case CmpInst::ICMP_UGE:
2736  case CmpInst::ICMP_ULT:
2737  case CmpInst::ICMP_ULE:
2738  // However, we have to switch them to their signed variants to handle
2739  // negative indices from the base pointer.
2740  Pred = ICmpInst::getSignedPredicate(Pred);
2741  break;
2742  }
2743 
2744  // Strip off any constant offsets so that we can reason about them.
2745  // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2746  // here and compare base addresses like AliasAnalysis does, however there are
2747  // numerous hazards. AliasAnalysis and its utilities rely on special rules
2748  // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2749  // doesn't need to guarantee pointer inequality when it says NoAlias.
2750 
2751  // Even if an non-inbounds GEP occurs along the path we can still optimize
2752  // equality comparisons concerning the result.
2753  bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2754  APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2755  APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
2756 
2757  // If LHS and RHS are related via constant offsets to the same base
2758  // value, we can replace it with an icmp which just compares the offsets.
2759  if (LHS == RHS)
2761  ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2762 
2763  // Various optimizations for (in)equality comparisons.
2764  if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2765  // Different non-empty allocations that exist at the same time have
2766  // different addresses (if the program can tell). If the offsets are
2767  // within the bounds of their allocations (and not one-past-the-end!
2768  // so we can't use inbounds!), and their allocations aren't the same,
2769  // the pointers are not equal.
2771  uint64_t LHSSize, RHSSize;
2772  ObjectSizeOpts Opts;
2774  auto *F = [](Value *V) -> Function * {
2775  if (auto *I = dyn_cast<Instruction>(V))
2776  return I->getFunction();
2777  if (auto *A = dyn_cast<Argument>(V))
2778  return A->getParent();
2779  return nullptr;
2780  }(LHS);
2781  Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2782  if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2783  getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2784  !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2785  LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2787  !CmpInst::isTrueWhenEqual(Pred));
2788  }
2789  }
2790 
2791  // If one side of the equality comparison must come from a noalias call
2792  // (meaning a system memory allocation function), and the other side must
2793  // come from a pointer that cannot overlap with dynamically-allocated
2794  // memory within the lifetime of the current function (allocas, byval
2795  // arguments, globals), then determine the comparison result here.
2796  SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2797  getUnderlyingObjects(LHS, LHSUObjs);
2798  getUnderlyingObjects(RHS, RHSUObjs);
2799 
2800  // Is the set of underlying objects all noalias calls?
2801  auto IsNAC = [](ArrayRef<const Value *> Objects) {
2802  return all_of(Objects, isNoAliasCall);
2803  };
2804 
2805  // Is the set of underlying objects all things which must be disjoint from
2806  // noalias calls. We assume that indexing from such disjoint storage
2807  // into the heap is undefined, and thus offsets can be safely ignored.
2808  auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2809  return all_of(Objects, ::isAllocDisjoint);
2810  };
2811 
2812  if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2813  (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2815  !CmpInst::isTrueWhenEqual(Pred));
2816 
2817  // Fold comparisons for non-escaping pointer even if the allocation call
2818  // cannot be elided. We cannot fold malloc comparison to null. Also, the
2819  // dynamic allocation call could be either of the operands. Note that
2820  // the other operand can not be based on the alloc - if it were, then
2821  // the cmp itself would be a capture.
2822  Value *MI = nullptr;
2823  if (isAllocLikeFn(LHS, TLI) &&
2824  llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2825  MI = LHS;
2826  else if (isAllocLikeFn(RHS, TLI) &&
2827  llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2828  MI = RHS;
2829  // FIXME: We should also fold the compare when the pointer escapes, but the
2830  // compare dominates the pointer escape
2831  if (MI && !PointerMayBeCaptured(MI, true, true))
2834  }
2835 
2836  // Otherwise, fail.
2837  return nullptr;
2838 }
2839 
2840 /// Fold an icmp when its operands have i1 scalar type.
2842  Value *RHS, const SimplifyQuery &Q) {
2843  Type *ITy = getCompareTy(LHS); // The return type.
2844  Type *OpTy = LHS->getType(); // The operand type.
2845  if (!OpTy->isIntOrIntVectorTy(1))
2846  return nullptr;
2847 
2848  // A boolean compared to true/false can be reduced in 14 out of the 20
2849  // (10 predicates * 2 constants) possible combinations. The other
2850  // 6 cases require a 'not' of the LHS.
2851 
2852  auto ExtractNotLHS = [](Value *V) -> Value * {
2853  Value *X;
2854  if (match(V, m_Not(m_Value(X))))
2855  return X;
2856  return nullptr;
2857  };
2858 
2859  if (match(RHS, m_Zero())) {
2860  switch (Pred) {
2861  case CmpInst::ICMP_NE: // X != 0 -> X
2862  case CmpInst::ICMP_UGT: // X >u 0 -> X
2863  case CmpInst::ICMP_SLT: // X <s 0 -> X
2864  return LHS;
2865 
2866  case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X
2867  case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2868  case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2869  if (Value *X = ExtractNotLHS(LHS))
2870  return X;
2871  break;
2872 
2873  case CmpInst::ICMP_ULT: // X <u 0 -> false
2874  case CmpInst::ICMP_SGT: // X >s 0 -> false
2875  return getFalse(ITy);
2876 
2877  case CmpInst::ICMP_UGE: // X >=u 0 -> true
2878  case CmpInst::ICMP_SLE: // X <=s 0 -> true
2879  return getTrue(ITy);
2880 
2881  default:
2882  break;
2883  }
2884  } else if (match(RHS, m_One())) {
2885  switch (Pred) {
2886  case CmpInst::ICMP_EQ: // X == 1 -> X
2887  case CmpInst::ICMP_UGE: // X >=u 1 -> X
2888  case CmpInst::ICMP_SLE: // X <=s -1 -> X
2889  return LHS;
2890 
2891  case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X
2892  case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X
2893  case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X
2894  if (Value *X = ExtractNotLHS(LHS))
2895  return X;
2896  break;
2897 
2898  case CmpInst::ICMP_UGT: // X >u 1 -> false
2899  case CmpInst::ICMP_SLT: // X <s -1 -> false
2900  return getFalse(ITy);
2901 
2902  case CmpInst::ICMP_ULE: // X <=u 1 -> true
2903  case CmpInst::ICMP_SGE: // X >=s -1 -> true
2904  return getTrue(ITy);
2905 
2906  default:
2907  break;
2908  }
2909  }
2910 
2911  switch (Pred) {
2912  default:
2913  break;
2914  case ICmpInst::ICMP_UGE:
2915  if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2916  return getTrue(ITy);
2917  break;
2918  case ICmpInst::ICMP_SGE:
2919  /// For signed comparison, the values for an i1 are 0 and -1
2920  /// respectively. This maps into a truth table of:
2921  /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2922  /// 0 | 0 | 1 (0 >= 0) | 1
2923  /// 0 | 1 | 1 (0 >= -1) | 1
2924  /// 1 | 0 | 0 (-1 >= 0) | 0
2925  /// 1 | 1 | 1 (-1 >= -1) | 1
2926  if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2927  return getTrue(ITy);
2928  break;
2929  case ICmpInst::ICMP_ULE:
2930  if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2931  return getTrue(ITy);
2932  break;
2933  case ICmpInst::ICMP_SLE:
2934  /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2935  if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2936  return getTrue(ITy);
2937  break;
2938  }
2939 
2940  return nullptr;
2941 }
2942 
2943 /// Try hard to fold icmp with zero RHS because this is a common case.
2945  Value *RHS, const SimplifyQuery &Q) {
2946  if (!match(RHS, m_Zero()))
2947  return nullptr;
2948 
2949  Type *ITy = getCompareTy(LHS); // The return type.
2950  switch (Pred) {
2951  default:
2952  llvm_unreachable("Unknown ICmp predicate!");
2953  case ICmpInst::ICMP_ULT:
2954  return getFalse(ITy);
2955  case ICmpInst::ICMP_UGE:
2956  return getTrue(ITy);
2957  case ICmpInst::ICMP_EQ:
2958  case ICmpInst::ICMP_ULE:
2959  if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2960  return getFalse(ITy);
2961  break;
2962  case ICmpInst::ICMP_NE:
2963  case ICmpInst::ICMP_UGT:
2964  if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2965  return getTrue(ITy);
2966  break;
2967  case ICmpInst::ICMP_SLT: {
2968  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2969  if (LHSKnown.isNegative())
2970  return getTrue(ITy);
2971  if (LHSKnown.isNonNegative())
2972  return getFalse(ITy);
2973  break;
2974  }
2975  case ICmpInst::ICMP_SLE: {
2976  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2977  if (LHSKnown.isNegative())
2978  return getTrue(ITy);
2979  if (LHSKnown.isNonNegative() &&
2980  isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2981  return getFalse(ITy);
2982  break;
2983  }
2984  case ICmpInst::ICMP_SGE: {
2985  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2986  if (LHSKnown.isNegative())
2987  return getFalse(ITy);
2988  if (LHSKnown.isNonNegative())
2989  return getTrue(ITy);
2990  break;
2991  }
2992  case ICmpInst::ICMP_SGT: {
2993  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2994  if (LHSKnown.isNegative())
2995  return getFalse(ITy);
2996  if (LHSKnown.isNonNegative() &&
2997  isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2998  return getTrue(ITy);
2999  break;
3000  }
3001  }
3002 
3003  return nullptr;
3004 }
3005 
3007  Value *RHS, const InstrInfoQuery &IIQ) {
3008  Type *ITy = getCompareTy(RHS); // The return type.
3009 
3010  Value *X;
3011  // Sign-bit checks can be optimized to true/false after unsigned
3012  // floating-point casts:
3013  // icmp slt (bitcast (uitofp X)), 0 --> false
3014  // icmp sgt (bitcast (uitofp X)), -1 --> true
3015  if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
3016  if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
3017  return ConstantInt::getFalse(ITy);
3018  if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
3019  return ConstantInt::getTrue(ITy);
3020  }
3021 
3022  const APInt *C;
3023  if (!match(RHS, m_APIntAllowUndef(C)))
3024  return nullptr;
3025 
3026  // Rule out tautological comparisons (eg., ult 0 or uge 0).
3028  if (RHS_CR.isEmptySet())
3029  return ConstantInt::getFalse(ITy);
3030  if (RHS_CR.isFullSet())
3031  return ConstantInt::getTrue(ITy);
3032 
3033  ConstantRange LHS_CR =
3035  if (!LHS_CR.isFullSet()) {
3036  if (RHS_CR.contains(LHS_CR))
3037  return ConstantInt::getTrue(ITy);
3038  if (RHS_CR.inverse().contains(LHS_CR))
3039  return ConstantInt::getFalse(ITy);
3040  }
3041 
3042  // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC)
3043  // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3044  const APInt *MulC;
3045  if (ICmpInst::isEquality(Pred) &&
3046  ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3047  *MulC != 0 && C->urem(*MulC) != 0) ||
3048  (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3049  *MulC != 0 && C->srem(*MulC) != 0)))
3050  return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
3051 
3052  return nullptr;
3053 }
3054 
3056  BinaryOperator *LBO, Value *RHS,
3057  const SimplifyQuery &Q,
3058  unsigned MaxRecurse) {
3059  Type *ITy = getCompareTy(RHS); // The return type.
3060 
3061  Value *Y = nullptr;
3062  // icmp pred (or X, Y), X
3063  if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3064  if (Pred == ICmpInst::ICMP_ULT)
3065  return getFalse(ITy);
3066  if (Pred == ICmpInst::ICMP_UGE)
3067  return getTrue(ITy);
3068 
3069  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3070  KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3071  KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3072  if (RHSKnown.isNonNegative() && YKnown.isNegative())
3073  return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3074  if (RHSKnown.isNegative() || YKnown.isNonNegative())
3075  return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3076  }
3077  }
3078 
3079  // icmp pred (and X, Y), X
3080  if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
3081  if (Pred == ICmpInst::ICMP_UGT)
3082  return getFalse(ITy);
3083  if (Pred == ICmpInst::ICMP_ULE)
3084  return getTrue(ITy);
3085  }
3086 
3087  // icmp pred (urem X, Y), Y
3088  if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3089  switch (Pred) {
3090  default:
3091  break;
3092  case ICmpInst::ICMP_SGT:
3093  case ICmpInst::ICMP_SGE: {
3094  KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3095  if (!Known.isNonNegative())
3096  break;
3097  [[fallthrough]];
3098  }
3099  case ICmpInst::ICMP_EQ:
3100  case ICmpInst::ICMP_UGT:
3101  case ICmpInst::ICMP_UGE:
3102  return getFalse(ITy);
3103  case ICmpInst::ICMP_SLT:
3104  case ICmpInst::ICMP_SLE: {
3105  KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3106  if (!Known.isNonNegative())
3107  break;
3108  [[fallthrough]];
3109  }
3110  case ICmpInst::ICMP_NE:
3111  case ICmpInst::ICMP_ULT:
3112  case ICmpInst::ICMP_ULE:
3113  return getTrue(ITy);
3114  }
3115  }
3116 
3117  // icmp pred (urem X, Y), X
3118  if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3119  if (Pred == ICmpInst::ICMP_ULE)
3120  return getTrue(ITy);
3121  if (Pred == ICmpInst::ICMP_UGT)
3122  return getFalse(ITy);
3123  }
3124 
3125  // x >>u y <=u x --> true.
3126  // x >>u y >u x --> false.
3127  // x udiv y <=u x --> true.
3128  // x udiv y >u x --> false.
3129  if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3130  match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3131  // icmp pred (X op Y), X
3132  if (Pred == ICmpInst::ICMP_UGT)
3133  return getFalse(ITy);
3134  if (Pred == ICmpInst::ICMP_ULE)
3135  return getTrue(ITy);
3136  }
3137 
3138  // If x is nonzero:
3139  // x >>u C <u x --> true for C != 0.
3140  // x >>u C != x --> true for C != 0.
3141  // x >>u C >=u x --> false for C != 0.
3142  // x >>u C == x --> false for C != 0.
3143  // x udiv C <u x --> true for C != 1.
3144  // x udiv C != x --> true for C != 1.
3145  // x udiv C >=u x --> false for C != 1.
3146  // x udiv C == x --> false for C != 1.
3147  // TODO: allow non-constant shift amount/divisor
3148  const APInt *C;
3149  if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3150  (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3151  if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3152  switch (Pred) {
3153  default:
3154  break;
3155  case ICmpInst::ICMP_EQ:
3156  case ICmpInst::ICMP_UGE:
3157  return getFalse(ITy);
3158  case ICmpInst::ICMP_NE:
3159  case ICmpInst::ICMP_ULT:
3160  return getTrue(ITy);
3161  case ICmpInst::ICMP_UGT:
3162  case ICmpInst::ICMP_ULE:
3163  // UGT/ULE are handled by the more general case just above
3164  llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3165  }
3166  }
3167  }
3168 
3169  // (x*C1)/C2 <= x for C1 <= C2.
3170  // This holds even if the multiplication overflows: Assume that x != 0 and
3171  // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3172  // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3173  //
3174  // Additionally, either the multiplication and division might be represented
3175  // as shifts:
3176  // (x*C1)>>C2 <= x for C1 < 2**C2.
3177  // (x<<C1)/C2 <= x for 2**C1 < C2.
3178  const APInt *C1, *C2;
3179  if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3180  C1->ule(*C2)) ||
3181  (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3182  C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3183  (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3184  (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3185  if (Pred == ICmpInst::ICMP_UGT)
3186  return getFalse(ITy);
3187  if (Pred == ICmpInst::ICMP_ULE)
3188  return getTrue(ITy);
3189  }
3190 
3191  // (sub C, X) == X, C is odd --> false
3192  // (sub C, X) != X, C is odd --> true
3193  if (match(LBO, m_Sub(m_APIntAllowUndef(C), m_Specific(RHS))) &&
3194  (*C & 1) == 1 && ICmpInst::isEquality(Pred))
3195  return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
3196 
3197  return nullptr;
3198 }
3199 
3200 // If only one of the icmp's operands has NSW flags, try to prove that:
3201 //
3202 // icmp slt (x + C1), (x +nsw C2)
3203 //
3204 // is equivalent to:
3205 //
3206 // icmp slt C1, C2
3207 //
3208 // which is true if x + C2 has the NSW flags set and:
3209 // *) C1 < C2 && C1 >= 0, or
3210 // *) C2 < C1 && C1 <= 0.
3211 //
3213  Value *RHS) {
3214  // TODO: only support icmp slt for now.
3215  if (Pred != CmpInst::ICMP_SLT)
3216  return false;
3217 
3218  // Canonicalize nsw add as RHS.
3219  if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3220  std::swap(LHS, RHS);
3221  if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3222  return false;
3223 
3224  Value *X;
3225  const APInt *C1, *C2;
3226  if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3227  !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3228  return false;
3229 
3230  return (C1->slt(*C2) && C1->isNonNegative()) ||
3231  (C2->slt(*C1) && C1->isNonPositive());
3232 }
3233 
3234 /// TODO: A large part of this logic is duplicated in InstCombine's
3235 /// foldICmpBinOp(). We should be able to share that and avoid the code
3236 /// duplication.
3238  Value *RHS, const SimplifyQuery &Q,
3239  unsigned MaxRecurse) {
3240  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3241  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3242  if (MaxRecurse && (LBO || RBO)) {
3243  // Analyze the case when either LHS or RHS is an add instruction.
3244  Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3245  // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3246  bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3247  if (LBO && LBO->getOpcode() == Instruction::Add) {
3248  A = LBO->getOperand(0);
3249  B = LBO->getOperand(1);
3250  NoLHSWrapProblem =
3251  ICmpInst::isEquality(Pred) ||
3252  (CmpInst::isUnsigned(Pred) &&
3253  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3254  (CmpInst::isSigned(Pred) &&
3255  Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3256  }
3257  if (RBO && RBO->getOpcode() == Instruction::Add) {
3258  C = RBO->getOperand(0);
3259  D = RBO->getOperand(1);
3260  NoRHSWrapProblem =
3261  ICmpInst::isEquality(Pred) ||
3262  (CmpInst::isUnsigned(Pred) &&
3263  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3264  (CmpInst::isSigned(Pred) &&
3265  Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3266  }
3267 
3268  // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3269  if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3270  if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
3272  MaxRecurse - 1))
3273  return V;
3274 
3275  // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3276  if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3277  if (Value *V =
3279  C == LHS ? D : C, Q, MaxRecurse - 1))
3280  return V;
3281 
3282  // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3283  bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3285  if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3286  // Determine Y and Z in the form icmp (X+Y), (X+Z).
3287  Value *Y, *Z;
3288  if (A == C) {
3289  // C + B == C + D -> B == D
3290  Y = B;
3291  Z = D;
3292  } else if (A == D) {
3293  // D + B == C + D -> B == C
3294  Y = B;
3295  Z = C;
3296  } else if (B == C) {
3297  // A + C == C + D -> A == D
3298  Y = A;
3299  Z = D;
3300  } else {
3301  assert(B == D);
3302  // A + D == C + D -> A == C
3303  Y = A;
3304  Z = C;
3305  }
3306  if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3307  return V;
3308  }
3309  }
3310 
3311  if (LBO)
3312  if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3313  return V;
3314 
3315  if (RBO)
3317  ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3318  return V;
3319 
3320  // 0 - (zext X) pred C
3321  if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3322  const APInt *C;
3323  if (match(RHS, m_APInt(C))) {
3324  if (C->isStrictlyPositive()) {
3325  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3327  if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3329  }
3330  if (C->isNonNegative()) {
3331  if (Pred == ICmpInst::ICMP_SLE)
3333  if (Pred == ICmpInst::ICMP_SGT)
3335  }
3336  }
3337  }
3338 
3339  // If C2 is a power-of-2 and C is not:
3340  // (C2 << X) == C --> false
3341  // (C2 << X) != C --> true
3342  const APInt *C;
3343  if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3344  match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3345  // C2 << X can equal zero in some circumstances.
3346  // This simplification might be unsafe if C is zero.
3347  //
3348  // We know it is safe if:
3349  // - The shift is nsw. We can't shift out the one bit.
3350  // - The shift is nuw. We can't shift out the one bit.
3351  // - C2 is one.
3352  // - C isn't zero.
3353  if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3354  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3355  match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3356  if (Pred == ICmpInst::ICMP_EQ)
3358  if (Pred == ICmpInst::ICMP_NE)
3360  }
3361  }
3362 
3363  // TODO: This is overly constrained. LHS can be any power-of-2.
3364  // (1 << X) >u 0x8000 --> false
3365  // (1 << X) <=u 0x8000 --> true
3366  if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
3367  if (Pred == ICmpInst::ICMP_UGT)
3369  if (Pred == ICmpInst::ICMP_ULE)
3371  }
3372 
3373  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3374  LBO->getOperand(1) == RBO->getOperand(1)) {
3375  switch (LBO->getOpcode()) {
3376  default:
3377  break;
3378  case Instruction::UDiv:
3379  case Instruction::LShr:
3380  if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3381  !Q.IIQ.isExact(RBO))
3382  break;
3383  if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3384  RBO->getOperand(0), Q, MaxRecurse - 1))
3385  return V;
3386  break;
3387  case Instruction::SDiv:
3388  if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3389  !Q.IIQ.isExact(RBO))
3390  break;
3391  if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3392  RBO->getOperand(0), Q, MaxRecurse - 1))
3393  return V;
3394  break;
3395  case Instruction::AShr:
3396  if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3397  break;
3398  if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3399  RBO->getOperand(0), Q, MaxRecurse - 1))
3400  return V;
3401  break;
3402  case Instruction::Shl: {
3403  bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3404  bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3405  if (!NUW && !NSW)
3406  break;
3407  if (!NSW && ICmpInst::isSigned(Pred))
3408  break;
3409  if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3410  RBO->getOperand(0), Q, MaxRecurse - 1))
3411  return V;
3412  break;
3413  }
3414  }
3415  }
3416  return nullptr;
3417 }
3418 
3419 /// simplify integer comparisons where at least one operand of the compare
3420 /// matches an integer min/max idiom.
3422  Value *RHS, const SimplifyQuery &Q,
3423  unsigned MaxRecurse) {
3424  Type *ITy = getCompareTy(LHS); // The return type.
3425  Value *A, *B;
3427  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3428 
3429  // Signed variants on "max(a,b)>=a -> true".
3430  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3431  if (A != RHS)
3432  std::swap(A, B); // smax(A, B) pred A.
3433  EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3434  // We analyze this as smax(A, B) pred A.
3435  P = Pred;
3436  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3437  (A == LHS || B == LHS)) {
3438  if (A != LHS)
3439  std::swap(A, B); // A pred smax(A, B).
3440  EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3441  // We analyze this as smax(A, B) swapped-pred A.
3443  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3444  (A == RHS || B == RHS)) {
3445  if (A != RHS)
3446  std::swap(A, B); // smin(A, B) pred A.
3447  EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3448  // We analyze this as smax(-A, -B) swapped-pred -A.
3449  // Note that we do not need to actually form -A or -B thanks to EqP.
3451  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3452  (A == LHS || B == LHS)) {
3453  if (A != LHS)
3454  std::swap(A, B); // A pred smin(A, B).
3455  EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3456  // We analyze this as smax(-A, -B) pred -A.
3457  // Note that we do not need to actually form -A or -B thanks to EqP.
3458  P = Pred;
3459  }
3460  if (P != CmpInst::BAD_ICMP_PREDICATE) {
3461  // Cases correspond to "max(A, B) p A".
3462  switch (P) {
3463  default:
3464  break;
3465  case CmpInst::ICMP_EQ:
3466  case CmpInst::ICMP_SLE:
3467  // Equivalent to "A EqP B". This may be the same as the condition tested
3468  // in the max/min; if so, we can just return that.
3469  if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3470  return V;
3471  if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3472  return V;
3473  // Otherwise, see if "A EqP B" simplifies.
3474  if (MaxRecurse)
3475  if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3476  return V;
3477  break;
3478  case CmpInst::ICMP_NE:
3479  case CmpInst::ICMP_SGT: {
3481  // Equivalent to "A InvEqP B". This may be the same as the condition
3482  // tested in the max/min; if so, we can just return that.
3483  if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3484  return V;
3485  if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3486  return V;
3487  // Otherwise, see if "A InvEqP B" simplifies.
3488  if (MaxRecurse)
3489  if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3490  return V;
3491  break;
3492  }
3493  case CmpInst::ICMP_SGE:
3494  // Always true.
3495  return getTrue(ITy);
3496  case CmpInst::ICMP_SLT:
3497  // Always false.
3498  return getFalse(ITy);
3499  }
3500  }
3501 
3502  // Unsigned variants on "max(a,b)>=a -> true".
3504  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3505  if (A != RHS)
3506  std::swap(A, B); // umax(A, B) pred A.
3507  EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3508  // We analyze this as umax(A, B) pred A.
3509  P = Pred;
3510  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3511  (A == LHS || B == LHS)) {
3512  if (A != LHS)
3513  std::swap(A, B); // A pred umax(A, B).
3514  EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3515  // We analyze this as umax(A, B) swapped-pred A.
3517  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3518  (A == RHS || B == RHS)) {
3519  if (A != RHS)
3520  std::swap(A, B); // umin(A, B) pred A.
3521  EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3522  // We analyze this as umax(-A, -B) swapped-pred -A.
3523  // Note that we do not need to actually form -A or -B thanks to EqP.
3525  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3526  (A == LHS || B == LHS)) {
3527  if (A != LHS)
3528  std::swap(A, B); // A pred umin(A, B).
3529  EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3530  // We analyze this as umax(-A, -B) pred -A.
3531  // Note that we do not need to actually form -A or -B thanks to EqP.
3532  P = Pred;
3533  }
3534  if (P != CmpInst::BAD_ICMP_PREDICATE) {
3535  // Cases correspond to "max(A, B) p A".
3536  switch (P) {
3537  default:
3538  break;
3539  case CmpInst::ICMP_EQ:
3540  case CmpInst::ICMP_ULE:
3541  // Equivalent to "A EqP B". This may be the same as the condition tested
3542  // in the max/min; if so, we can just return that.
3543  if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3544  return V;
3545  if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3546  return V;
3547  // Otherwise, see if "A EqP B" simplifies.
3548  if (MaxRecurse)
3549  if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3550  return V;
3551  break;
3552  case CmpInst::ICMP_NE:
3553  case CmpInst::ICMP_UGT: {
3555  // Equivalent to "A InvEqP B". This may be the same as the condition
3556  // tested in the max/min; if so, we can just return that.
3557  if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3558  return V;
3559  if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3560  return V;
3561  // Otherwise, see if "A InvEqP B" simplifies.
3562  if (MaxRecurse)
3563  if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3564  return V;
3565  break;
3566  }
3567  case CmpInst::ICMP_UGE:
3568  return getTrue(ITy);
3569  case CmpInst::ICMP_ULT:
3570  return getFalse(ITy);
3571  }
3572  }
3573 
3574  // Comparing 1 each of min/max with a common operand?
3575  // Canonicalize min operand to RHS.
3576  if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3577  match(LHS, m_SMin(m_Value(), m_Value()))) {
3578  std::swap(LHS, RHS);
3579  Pred = ICmpInst::getSwappedPredicate(Pred);
3580  }
3581 
3582  Value *C, *D;
3583  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3584  match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3585  (A == C || A == D || B == C || B == D)) {
3586  // smax(A, B) >=s smin(A, D) --> true
3587  if (Pred == CmpInst::ICMP_SGE)
3588  return getTrue(ITy);
3589  // smax(A, B) <s smin(A, D) --> false
3590  if (Pred == CmpInst::ICMP_SLT)
3591  return getFalse(ITy);
3592  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3593  match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3594  (A == C || A == D || B == C || B == D)) {
3595  // umax(A, B) >=u umin(A, D) --> true
3596  if (Pred == CmpInst::ICMP_UGE)
3597  return getTrue(ITy);
3598  // umax(A, B) <u umin(A, D) --> false
3599  if (Pred == CmpInst::ICMP_ULT)
3600  return getFalse(ITy);
3601  }
3602 
3603  return nullptr;
3604 }
3605 
3607  Value *LHS, Value *RHS,
3608  const SimplifyQuery &Q) {
3609  // Gracefully handle instructions that have not been inserted yet.
3610  if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3611  return nullptr;
3612 
3613  for (Value *AssumeBaseOp : {LHS, RHS}) {
3614  for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3615  if (!AssumeVH)
3616  continue;
3617 
3618  CallInst *Assume = cast<CallInst>(AssumeVH);
3619  if (Optional<bool> Imp = isImpliedCondition(Assume->getArgOperand(0),
3620  Predicate, LHS, RHS, Q.DL))
3621  if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3622  return ConstantInt::get(getCompareTy(LHS), *Imp);
3623  }
3624  }
3625 
3626  return nullptr;
3627 }
3628 
3629 /// Given operands for an ICmpInst, see if we can fold the result.
3630 /// If not, this returns null.
3632  const SimplifyQuery &Q, unsigned MaxRecurse) {
3634  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3635 
3636  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3637  if (Constant *CRHS = dyn_cast<Constant>(RHS))
3638  return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3639 
3640  // If we have a constant, make sure it is on the RHS.
3641  std::swap(LHS, RHS);
3642  Pred = CmpInst::getSwappedPredicate(Pred);
3643  }
3644  assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3645 
3646  Type *ITy = getCompareTy(LHS); // The return type.
3647 
3648  // icmp poison, X -> poison
3649  if (isa<PoisonValue>(RHS))
3650  return PoisonValue::get(ITy);
3651 
3652  // For EQ and NE, we can always pick a value for the undef to make the
3653  // predicate pass or fail, so we can return undef.
3654  // Matches behavior in llvm::ConstantFoldCompareInstruction.
3655  if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3656  return UndefValue::get(ITy);
3657 
3658  // icmp X, X -> true/false
3659  // icmp X, undef -> true/false because undef could be X.
3660  if (LHS == RHS || Q.isUndefValue(RHS))
3661  return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3662 
3663  if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3664  return V;
3665 
3666  // TODO: Sink/common this with other potentially expensive calls that use
3667  // ValueTracking? See comment below for isKnownNonEqual().
3668  if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3669  return V;
3670 
3671  if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3672  return V;
3673 
3674  // If both operands have range metadata, use the metadata
3675  // to simplify the comparison.
3676  if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3677  auto RHS_Instr = cast<Instruction>(RHS);
3678  auto LHS_Instr = cast<Instruction>(LHS);
3679 
3680  if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3681  Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3682  auto RHS_CR = getConstantRangeFromMetadata(
3683  *RHS_Instr->getMetadata(LLVMContext::MD_range));
3684  auto LHS_CR = getConstantRangeFromMetadata(
3685  *LHS_Instr->getMetadata(LLVMContext::MD_range));
3686 
3687  if (LHS_CR.icmp(Pred, RHS_CR))
3688  return ConstantInt::getTrue(RHS->getContext());
3689 
3690  if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3692  }
3693  }
3694 
3695  // Compare of cast, for example (zext X) != 0 -> X != 0
3696  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3697  Instruction *LI = cast<CastInst>(LHS);
3698  Value *SrcOp = LI->getOperand(0);
3699  Type *SrcTy = SrcOp->getType();
3700  Type *DstTy = LI->getType();
3701 
3702  // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3703  // if the integer type is the same size as the pointer type.
3704  if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3705  Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3706  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3707  // Transfer the cast to the constant.
3708  if (Value *V = simplifyICmpInst(Pred, SrcOp,
3709  ConstantExpr::getIntToPtr(RHSC, SrcTy),
3710  Q, MaxRecurse - 1))
3711  return V;
3712  } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3713  if (RI->getOperand(0)->getType() == SrcTy)
3714  // Compare without the cast.
3715  if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3716  MaxRecurse - 1))
3717  return V;
3718  }
3719  }
3720 
3721  if (isa<ZExtInst>(LHS)) {
3722  // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3723  // same type.
3724  if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3725  if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3726  // Compare X and Y. Note that signed predicates become unsigned.
3727  if (Value *V =
3729  RI->getOperand(0), Q, MaxRecurse - 1))
3730  return V;
3731  }
3732  // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3733  else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3734  if (SrcOp == RI->getOperand(0)) {
3735  if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3736  return ConstantInt::getTrue(ITy);
3737  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3738  return ConstantInt::getFalse(ITy);
3739  }
3740  }
3741  // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3742  // too. If not, then try to deduce the result of the comparison.
3743  else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3744  // Compute the constant that would happen if we truncated to SrcTy then
3745  // reextended to DstTy.
3746  Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3747  Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3748 
3749  // If the re-extended constant didn't change then this is effectively
3750  // also a case of comparing two zero-extended values.
3751  if (RExt == CI && MaxRecurse)
3753  SrcOp, Trunc, Q, MaxRecurse - 1))
3754  return V;
3755 
3756  // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3757  // there. Use this to work out the result of the comparison.
3758  if (RExt != CI) {
3759  switch (Pred) {
3760  default:
3761  llvm_unreachable("Unknown ICmp predicate!");
3762  // LHS <u RHS.
3763  case ICmpInst::ICMP_EQ:
3764  case ICmpInst::ICMP_UGT:
3765  case ICmpInst::ICMP_UGE:
3766  return ConstantInt::getFalse(CI->getContext());
3767 
3768  case ICmpInst::ICMP_NE:
3769  case ICmpInst::ICMP_ULT:
3770  case ICmpInst::ICMP_ULE:
3771  return ConstantInt::getTrue(CI->getContext());
3772 
3773  // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3774  // is non-negative then LHS <s RHS.
3775  case ICmpInst::ICMP_SGT:
3776  case ICmpInst::ICMP_SGE:
3777  return CI->getValue().isNegative()
3778  ? ConstantInt::getTrue(CI->getContext())
3779  : ConstantInt::getFalse(CI->getContext());
3780 
3781  case ICmpInst::ICMP_SLT:
3782  case ICmpInst::ICMP_SLE:
3783  return CI->getValue().isNegative()
3784  ? ConstantInt::getFalse(CI->getContext())
3785  : ConstantInt::getTrue(CI->getContext());
3786  }
3787  }
3788  }
3789  }
3790 
3791  if (isa<SExtInst>(LHS)) {
3792  // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3793  // same type.
3794  if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3795  if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3796  // Compare X and Y. Note that the predicate does not change.
3797  if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3798  MaxRecurse - 1))
3799  return V;
3800  }
3801  // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3802  else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3803  if (SrcOp == RI->getOperand(0)) {
3804  if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3805  return ConstantInt::getTrue(ITy);
3806  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3807  return ConstantInt::getFalse(ITy);
3808  }
3809  }
3810  // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3811  // too. If not, then try to deduce the result of the comparison.
3812  else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3813  // Compute the constant that would happen if we truncated to SrcTy then
3814  // reextended to DstTy.
3815  Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3816  Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3817 
3818  // If the re-extended constant didn't change then this is effectively
3819  // also a case of comparing two sign-extended values.
3820  if (RExt == CI && MaxRecurse)
3821  if (Value *V =
3822  simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
3823  return V;
3824 
3825  // Otherwise the upper bits of LHS are all equal, while RHS has varying
3826  // bits there. Use this to work out the result of the comparison.
3827  if (RExt != CI) {
3828  switch (Pred) {
3829  default:
3830  llvm_unreachable("Unknown ICmp predicate!");
3831  case ICmpInst::ICMP_EQ:
3832  return ConstantInt::getFalse(CI->getContext());
3833  case ICmpInst::ICMP_NE:
3834  return ConstantInt::getTrue(CI->getContext());
3835 
3836  // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3837  // LHS >s RHS.
3838  case ICmpInst::ICMP_SGT:
3839  case ICmpInst::ICMP_SGE:
3840  return CI->getValue().isNegative()
3841  ? ConstantInt::getTrue(CI->getContext())
3842  : ConstantInt::getFalse(CI->getContext());
3843  case ICmpInst::ICMP_SLT:
3844  case ICmpInst::ICMP_SLE:
3845  return CI->getValue().isNegative()
3846  ? ConstantInt::getFalse(CI->getContext())
3847  : ConstantInt::getTrue(CI->getContext());
3848 
3849  // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3850  // LHS >u RHS.
3851  case ICmpInst::ICMP_UGT:
3852  case ICmpInst::ICMP_UGE:
3853  // Comparison is true iff the LHS <s 0.
3854  if (MaxRecurse)
3856  Constant::getNullValue(SrcTy), Q,
3857  MaxRecurse - 1))
3858  return V;
3859  break;
3860  case ICmpInst::ICMP_ULT:
3861  case ICmpInst::ICMP_ULE:
3862  // Comparison is true iff the LHS >=s 0.
3863  if (MaxRecurse)
3865  Constant::getNullValue(SrcTy), Q,
3866  MaxRecurse - 1))
3867  return V;
3868  break;
3869  }
3870  }
3871  }
3872  }
3873  }
3874 
3875  // icmp eq|ne X, Y -> false|true if X != Y
3876  // This is potentially expensive, and we have already computedKnownBits for
3877  // compares with 0 above here, so only try this for a non-zero compare.
3878  if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
3879  isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3880  return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3881  }
3882 
3883  if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3884  return V;
3885 
3886  if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3887  return V;
3888 
3889  if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3890  return V;
3891 
3892  // Simplify comparisons of related pointers using a powerful, recursive
3893  // GEP-walk when we have target data available..
3894  if (LHS->getType()->isPointerTy())
3895  if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3896  return C;
3897  if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3898  if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3899  if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3900  Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3901  Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3902  Q.DL.getTypeSizeInBits(CRHS->getType()))
3903  if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3904  CRHS->getPointerOperand(), Q))
3905  return C;
3906 
3907  // If the comparison is with the result of a select instruction, check whether
3908  // comparing with either branch of the select always yields the same value.
3909  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3910  if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3911  return V;
3912 
3913  // If the comparison is with the result of a phi instruction, check whether
3914  // doing the compare with each incoming phi value yields a common result.
3915  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3916  if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3917  return V;
3918 
3919  return nullptr;
3920 }
3921 
3923  const SimplifyQuery &Q) {
3925 }
3926 
3927 /// Given operands for an FCmpInst, see if we can fold the result.
3928 /// If not, this returns null.
3930  FastMathFlags FMF, const SimplifyQuery &Q,
3931  unsigned MaxRecurse) {
3933  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3934 
3935  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3936  if (Constant *CRHS = dyn_cast<Constant>(RHS))
3937  return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
3938  Q.CxtI);
3939 
3940  // If we have a constant, make sure it is on the RHS.
3941  std::swap(LHS, RHS);
3942  Pred = CmpInst::getSwappedPredicate(Pred);
3943  }
3944 
3945  // Fold trivial predicates.
3946  Type *RetTy = getCompareTy(LHS);
3947  if (Pred == FCmpInst::FCMP_FALSE)
3948  return getFalse(RetTy);
3949  if (Pred == FCmpInst::FCMP_TRUE)
3950  return getTrue(RetTy);
3951 
3952  // Fold (un)ordered comparison if we can determine there are no NaNs.
3953  if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3954  if (FMF.noNaNs() ||
3956  return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3957 
3958  // NaN is unordered; NaN is not ordered.
3960  "Comparison must be either ordered or unordered");
3961  if (match(RHS, m_NaN()))
3962  return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3963 
3964  // fcmp pred x, poison and fcmp pred poison, x
3965  // fold to poison
3966  if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
3967  return PoisonValue::get(RetTy);
3968 
3969  // fcmp pred x, undef and fcmp pred undef, x
3970  // fold to true if unordered, false if ordered
3971  if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3972  // Choosing NaN for the undef will always make unordered comparison succeed
3973  // and ordered comparison fail.
3974  return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3975  }
3976 
3977  // fcmp x,x -> true/false. Not all compares are foldable.
3978  if (LHS == RHS) {
3979  if (CmpInst::isTrueWhenEqual(Pred))
3980  return getTrue(RetTy);
3981  if (CmpInst::isFalseWhenEqual(Pred))
3982  return getFalse(RetTy);
3983  }
3984 
3985  // Handle fcmp with constant RHS.
3986  // TODO: Use match with a specific FP value, so these work with vectors with
3987  // undef lanes.
3988  const APFloat *C;
3989  if (match(RHS, m_APFloat(C))) {
3990  // Check whether the constant is an infinity.
3991  if (C->isInfinity()) {
3992  if (C->isNegative()) {
3993  switch (Pred) {
3994  case FCmpInst::FCMP_OLT:
3995  // No value is ordered and less than negative infinity.
3996  return getFalse(RetTy);
3997  case FCmpInst::FCMP_UGE:
3998  // All values are unordered with or at least negative infinity.
3999  return getTrue(RetTy);
4000  default:
4001  break;
4002  }
4003  } else {
4004  switch (Pred) {
4005  case FCmpInst::FCMP_OGT:
4006  // No value is ordered and greater than infinity.
4007  return getFalse(RetTy);
4008  case FCmpInst::FCMP_ULE:
4009  // All values are unordered with and at most infinity.
4010  return getTrue(RetTy);
4011  default:
4012  break;
4013  }
4014  }
4015 
4016  // LHS == Inf
4017  if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
4018  return getFalse(RetTy);
4019  // LHS != Inf
4020  if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
4021  return getTrue(RetTy);
4022  // LHS == Inf || LHS == NaN
4023  if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
4024  isKnownNeverNaN(LHS, Q.TLI))
4025  return getFalse(RetTy);
4026  // LHS != Inf && LHS != NaN
4027  if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
4028  isKnownNeverNaN(LHS, Q.TLI))
4029  return getTrue(RetTy);
4030  }
4031  if (C->isNegative() && !C->isNegZero()) {
4032  assert(!C->isNaN() && "Unexpected NaN constant!");
4033  // TODO: We can catch more cases by using a range check rather than
4034  // relying on CannotBeOrderedLessThanZero.
4035  switch (Pred) {
4036  case FCmpInst::FCMP_UGE:
4037  case FCmpInst::FCMP_UGT:
4038  case FCmpInst::FCMP_UNE:
4039  // (X >= 0) implies (X > C) when (C < 0)
4041  return getTrue(RetTy);
4042  break;
4043  case FCmpInst::FCMP_OEQ:
4044  case FCmpInst::FCMP_OLE:
4045  case FCmpInst::FCMP_OLT:
4046  // (X >= 0) implies !(X < C) when (C < 0)
4048  return getFalse(RetTy);
4049  break;
4050  default:
4051  break;
4052  }
4053  }
4054 
4055  // Check comparison of [minnum/maxnum with constant] with other constant.
4056  const APFloat *C2;
4057  if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
4058  *C2 < *C) ||
4059  (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
4060  *C2 > *C)) {
4061  bool IsMaxNum =
4062  cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
4063  // The ordered relationship and minnum/maxnum guarantee that we do not
4064  // have NaN constants, so ordered/unordered preds are handled the same.
4065  switch (Pred) {
4066  case FCmpInst::FCMP_OEQ:
4067  case FCmpInst::FCMP_UEQ:
4068  // minnum(X, LesserC) == C --> false
4069  // maxnum(X, GreaterC) == C --> false
4070  return getFalse(RetTy);
4071  case FCmpInst::FCMP_ONE:
4072  case FCmpInst::FCMP_UNE:
4073  // minnum(X, LesserC) != C --> true
4074  // maxnum(X, GreaterC) != C --> true
4075  return getTrue(RetTy);
4076  case FCmpInst::FCMP_OGE:
4077  case FCmpInst::FCMP_UGE:
4078  case FCmpInst::FCMP_OGT:
4079  case FCmpInst::FCMP_UGT:
4080  // minnum(X, LesserC) >= C --> false
4081  // minnum(X, LesserC) > C --> false
4082  // maxnum(X, GreaterC) >= C --> true
4083  // maxnum(X, GreaterC) > C --> true
4084  return ConstantInt::get(RetTy, IsMaxNum);
4085  case FCmpInst::FCMP_OLE:
4086  case FCmpInst::FCMP_ULE:
4087  case FCmpInst::FCMP_OLT:
4088  case FCmpInst::FCMP_ULT:
4089  // minnum(X, LesserC) <= C --> true
4090  // minnum(X, LesserC) < C --> true
4091  // maxnum(X, GreaterC) <= C --> false
4092  // maxnum(X, GreaterC) < C --> false
4093  return ConstantInt::get(RetTy, !IsMaxNum);
4094  default:
4095  // TRUE/FALSE/ORD/UNO should be handled before this.
4096  llvm_unreachable("Unexpected fcmp predicate");
4097  }
4098  }
4099  }
4100 
4101  if (match(RHS, m_AnyZeroFP())) {
4102  switch (Pred) {
4103  case FCmpInst::FCMP_OGE:
4104  case FCmpInst::FCMP_ULT:
4105  // Positive or zero X >= 0.0 --> true
4106  // Positive or zero X < 0.0 --> false
4107  if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
4109  return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4110  break;
4111  case FCmpInst::FCMP_UGE:
4112  case FCmpInst::FCMP_OLT:
4113  // Positive or zero or nan X >= 0.0 --> true
4114  // Positive or zero or nan X < 0.0 --> false
4116  return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4117  break;
4118  default:
4119  break;
4120  }
4121  }
4122 
4123  // If the comparison is with the result of a select instruction, check whether
4124  // comparing with either branch of the select always yields the same value.
4125  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4126  if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4127  return V;
4128 
4129  // If the comparison is with the result of a phi instruction, check whether
4130  // doing the compare with each incoming phi value yields a common result.
4131  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4132  if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4133  return V;
4134 
4135  return nullptr;
4136 }
4137 
4139  FastMathFlags FMF, const SimplifyQuery &Q) {
4141 }
4142 
4144  const SimplifyQuery &Q,
4145  bool AllowRefinement,
4146  unsigned MaxRecurse) {
4147  // Trivial replacement.
4148  if (V == Op)
4149  return RepOp;
4150 
4151  // We cannot replace a constant, and shouldn't even try.
4152  if (isa<Constant>(Op))
4153  return nullptr;
4154 
4155  auto *I = dyn_cast<Instruction>(V);
4156  if (!I || !is_contained(I->operands(), Op))
4157  return nullptr;
4158 
4159  if (Op->getType()->isVectorTy()) {
4160  // For vector types, the simplification must hold per-lane, so forbid
4161  // potentially cross-lane operations like shufflevector.
4162  assert(I->getType()->isVectorTy() && "Vector type mismatch");
4163  if (isa<ShuffleVectorInst>(I) || isa<CallBase>(I))
4164  return nullptr;
4165  }
4166 
4167  // Replace Op with RepOp in instruction operands.
4168  SmallVector<Value *, 8> NewOps(I->getNumOperands());
4169  transform(I->operands(), NewOps.begin(),
4170  [&](Value *V) { return V == Op ? RepOp : V; });
4171 
4172  if (!AllowRefinement) {
4173  // General InstSimplify functions may refine the result, e.g. by returning
4174  // a constant for a potentially poison value. To avoid this, implement only
4175  // a few non-refining but profitable transforms here.
4176 
4177  if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4178  unsigned Opcode = BO->getOpcode();
4179  // id op x -> x, x op id -> x
4180  if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4181  return NewOps[1];
4182  if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4183  /* RHS */ true))
4184  return NewOps[0];
4185 
4186  // x & x -> x, x | x -> x
4187  if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4188  NewOps[0] == NewOps[1])
4189  return NewOps[0];
4190  }
4191 
4192  if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4193  // getelementptr x, 0 -> x
4194  if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
4195  !GEP->isInBounds())
4196  return NewOps[0];
4197  }
4198  } else if (MaxRecurse) {
4199  // The simplification queries below may return the original value. Consider:
4200  // %div = udiv i32 %arg, %arg2
4201  // %mul = mul nsw i32 %div, %arg2
4202  // %cmp = icmp eq i32 %mul, %arg
4203  // %sel = select i1 %cmp, i32 %div, i32 undef
4204  // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4205  // simplifies back to %arg. This can only happen because %mul does not
4206  // dominate %div. To ensure a consistent return value contract, we make sure
4207  // that this case returns nullptr as well.
4208  auto PreventSelfSimplify = [V](Value *Simplified) {
4209  return Simplified != V ? Simplified : nullptr;
4210  };
4211 
4212  if (auto *B = dyn_cast<BinaryOperator>(I))
4213  return PreventSelfSimplify(simplifyBinOp(B->getOpcode(), NewOps[0],
4214  NewOps[1], Q, MaxRecurse - 1));
4215 
4216  if (CmpInst *C = dyn_cast<CmpInst>(I))
4217  return PreventSelfSimplify(simplifyCmpInst(C->getPredicate(), NewOps[0],
4218  NewOps[1], Q, MaxRecurse - 1));
4219 
4220  if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4221  return PreventSelfSimplify(simplifyGEPInst(
4222  GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
4223  GEP->isInBounds(), Q, MaxRecurse - 1));
4224 
4225  if (isa<SelectInst>(I))
4226  return PreventSelfSimplify(simplifySelectInst(
4227  NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse - 1));
4228  // TODO: We could hand off more cases to instsimplify here.
4229  }
4230 
4231  // If all operands are constant after substituting Op for RepOp then we can
4232  // constant fold the instruction.
4233  SmallVector<Constant *, 8> ConstOps;
4234  for (Value *NewOp : NewOps) {
4235  if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4236  ConstOps.push_back(ConstOp);
4237  else
4238  return nullptr;
4239  }
4240 
4241  // Consider:
4242  // %cmp = icmp eq i32 %x, 2147483647
4243  // %add = add nsw i32 %x, 1
4244  // %sel = select i1 %cmp, i32 -2147483648, i32 %add
4245  //
4246  // We can't replace %sel with %add unless we strip away the flags (which
4247  // will be done in InstCombine).
4248  // TODO: This may be unsound, because it only catches some forms of
4249  // refinement.
4250  if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4251  return nullptr;
4252 
4253  return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4254 }
4255 
4257  const SimplifyQuery &Q,
4258  bool AllowRefinement) {
4259  return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4260  RecursionLimit);
4261 }
4262 
4263 /// Try to simplify a select instruction when its condition operand is an
4264 /// integer comparison where one operand of the compare is a constant.
4266  const APInt *Y, bool TrueWhenUnset) {
4267  const APInt *C;
4268 
4269  // (X & Y) == 0 ? X & ~Y : X --> X
4270  // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
4271  if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4272  *Y == ~*C)
4273  return TrueWhenUnset ? FalseVal : TrueVal;
4274 
4275  // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
4276  // (X & Y) != 0 ? X : X & ~Y --> X
4277  if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4278  *Y == ~*C)
4279  return TrueWhenUnset ? FalseVal : TrueVal;
4280 
4281  if (Y->isPowerOf2()) {
4282  // (X & Y) == 0 ? X | Y : X --> X | Y
4283  // (X & Y) != 0 ? X | Y : X --> X
4284  if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4285  *Y == *C)
4286  return TrueWhenUnset ? TrueVal : FalseVal;
4287 
4288  // (X & Y) == 0 ? X : X | Y --> X
4289  // (X & Y) != 0 ? X : X | Y --> X | Y
4290  if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4291  *Y == *C)
4292  return TrueWhenUnset ? TrueVal : FalseVal;
4293  }
4294 
4295  return nullptr;
4296 }
4297 
4298 static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4299  ICmpInst::Predicate Pred, Value *TVal,
4300  Value *FVal) {
4301  // Canonicalize common cmp+sel operand as CmpLHS.
4302  if (CmpRHS == TVal || CmpRHS == FVal) {
4303  std::swap(CmpLHS, CmpRHS);
4304  Pred = ICmpInst::getSwappedPredicate(Pred);
4305  }
4306 
4307  // Canonicalize common cmp+sel operand as TVal.
4308  if (CmpLHS == FVal) {
4309  std::swap(TVal, FVal);
4310  Pred = ICmpInst::getInversePredicate(Pred);
4311  }
4312 
4313  // A vector select may be shuffling together elements that are equivalent
4314  // based on the max/min/select relationship.
4315  Value *X = CmpLHS, *Y = CmpRHS;
4316  bool PeekedThroughSelectShuffle = false;
4317  auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
4318  if (Shuf && Shuf->isSelect()) {
4319  if (Shuf->getOperand(0) == Y)
4320  FVal = Shuf->getOperand(1);
4321  else if (Shuf->getOperand(1) == Y)
4322  FVal = Shuf->getOperand(0);
4323  else
4324  return nullptr;
4325  PeekedThroughSelectShuffle = true;
4326  }
4327 
4328  // (X pred Y) ? X : max/min(X, Y)
4329  auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
4330  if (!MMI || TVal != X ||
4331  !match(FVal, m_c_MaxOrMin(m_Specific(X), m_Specific(Y))))
4332  return nullptr;
4333 
4334  // (X > Y) ? X : max(X, Y) --> max(X, Y)
4335  // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4336  // (X < Y) ? X : min(X, Y) --> min(X, Y)
4337  // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4338  //
4339  // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4340  // (X > Y) ? X : (Z ? max(X, Y) : Y)
4341  // If Z is true, this reduces as above, and if Z is false:
4342  // (X > Y) ? X : Y --> max(X, Y)
4343  ICmpInst::Predicate MMPred = MMI->getPredicate();
4344  if (MMPred == CmpInst::getStrictPredicate(Pred))
4345  return MMI;
4346 
4347  // Other transforms are not valid with a shuffle.
4348  if (PeekedThroughSelectShuffle)
4349  return nullptr;
4350 
4351  // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
4352  if (Pred == CmpInst::ICMP_EQ)
4353  return MMI;
4354 
4355  // (X != Y) ? X : max/min(X, Y) --> X
4356  if (Pred == CmpInst::ICMP_NE)
4357  return X;
4358 
4359  // (X < Y) ? X : max(X, Y) --> X
4360  // (X <= Y) ? X : max(X, Y) --> X
4361  // (X > Y) ? X : min(X, Y) --> X
4362  // (X >= Y) ? X : min(X, Y) --> X
4364  if (MMPred == CmpInst::getStrictPredicate(InvPred))
4365  return X;
4366 
4367  return nullptr;
4368 }
4369 
4370 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4371 /// eq/ne.
4373  ICmpInst::Predicate Pred,
4374  Value *TrueVal, Value *FalseVal) {
4375  Value *X;
4376  APInt Mask;
4377  if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4378  return nullptr;
4379 
4381  Pred ==