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