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