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