[ARM] MVE sext costs
[llvm-complete.git] / lib / Analysis / InstructionSimplify.cpp
blob85002aafa8565285cd2d4dec278876ea5c65e5fb
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions. This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/CmpInstAnalysis.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/LoopAnalysisManager.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/IR/ConstantRange.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/KnownBits.h"
42 #include <algorithm>
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
46 #define DEBUG_TYPE "instsimplify"
48 enum { RecursionLimit = 3 };
50 STATISTIC(NumExpand, "Number of expansions");
51 STATISTIC(NumReassoc, "Number of reassociations");
53 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
54 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
55 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
56 const SimplifyQuery &, unsigned);
57 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
58 unsigned);
59 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
60 const SimplifyQuery &, unsigned);
61 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
62 unsigned);
63 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
64 const SimplifyQuery &Q, unsigned MaxRecurse);
65 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
66 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
67 static Value *SimplifyCastInst(unsigned, Value *, Type *,
68 const SimplifyQuery &, unsigned);
69 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
70 unsigned);
72 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
73 Value *FalseVal) {
74 BinaryOperator::BinaryOps BinOpCode;
75 if (auto *BO = dyn_cast<BinaryOperator>(Cond))
76 BinOpCode = BO->getOpcode();
77 else
78 return nullptr;
80 CmpInst::Predicate ExpectedPred, Pred1, Pred2;
81 if (BinOpCode == BinaryOperator::Or) {
82 ExpectedPred = ICmpInst::ICMP_NE;
83 } else if (BinOpCode == BinaryOperator::And) {
84 ExpectedPred = ICmpInst::ICMP_EQ;
85 } else
86 return nullptr;
88 // %A = icmp eq %TV, %FV
89 // %B = icmp eq %X, %Y (and one of these is a select operand)
90 // %C = and %A, %B
91 // %D = select %C, %TV, %FV
92 // -->
93 // %FV
95 // %A = icmp ne %TV, %FV
96 // %B = icmp ne %X, %Y (and one of these is a select operand)
97 // %C = or %A, %B
98 // %D = select %C, %TV, %FV
99 // -->
100 // %TV
101 Value *X, *Y;
102 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
103 m_Specific(FalseVal)),
104 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
105 Pred1 != Pred2 || Pred1 != ExpectedPred)
106 return nullptr;
108 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
109 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
111 return nullptr;
114 /// For a boolean type or a vector of boolean type, return false or a vector
115 /// with every element false.
116 static Constant *getFalse(Type *Ty) {
117 return ConstantInt::getFalse(Ty);
120 /// For a boolean type or a vector of boolean type, return true or a vector
121 /// with every element true.
122 static Constant *getTrue(Type *Ty) {
123 return ConstantInt::getTrue(Ty);
126 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
127 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
128 Value *RHS) {
129 CmpInst *Cmp = dyn_cast<CmpInst>(V);
130 if (!Cmp)
131 return false;
132 CmpInst::Predicate CPred = Cmp->getPredicate();
133 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
134 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
135 return true;
136 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
137 CRHS == LHS;
140 /// Does the given value dominate the specified phi node?
141 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
142 Instruction *I = dyn_cast<Instruction>(V);
143 if (!I)
144 // Arguments and constants dominate all instructions.
145 return true;
147 // If we are processing instructions (and/or basic blocks) that have not been
148 // fully added to a function, the parent nodes may still be null. Simply
149 // return the conservative answer in these cases.
150 if (!I->getParent() || !P->getParent() || !I->getFunction())
151 return false;
153 // If we have a DominatorTree then do a precise test.
154 if (DT)
155 return DT->dominates(I, P);
157 // Otherwise, if the instruction is in the entry block and is not an invoke,
158 // then it obviously dominates all phi nodes.
159 if (I->getParent() == &I->getFunction()->getEntryBlock() &&
160 !isa<InvokeInst>(I))
161 return true;
163 return false;
166 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
167 /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
168 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
169 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
170 /// Returns the simplified value, or null if no simplification was performed.
171 static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
172 Instruction::BinaryOps OpcodeToExpand,
173 const SimplifyQuery &Q, unsigned MaxRecurse) {
174 // Recursion is always used, so bail out at once if we already hit the limit.
175 if (!MaxRecurse--)
176 return nullptr;
178 // Check whether the expression has the form "(A op' B) op C".
179 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
180 if (Op0->getOpcode() == OpcodeToExpand) {
181 // It does! Try turning it into "(A op C) op' (B op C)".
182 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
183 // Do "A op C" and "B op C" both simplify?
184 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
185 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
186 // They do! Return "L op' R" if it simplifies or is already available.
187 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
188 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
189 && L == B && R == A)) {
190 ++NumExpand;
191 return LHS;
193 // Otherwise return "L op' R" if it simplifies.
194 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
195 ++NumExpand;
196 return V;
201 // Check whether the expression has the form "A op (B op' C)".
202 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
203 if (Op1->getOpcode() == OpcodeToExpand) {
204 // It does! Try turning it into "(A op B) op' (A op C)".
205 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
206 // Do "A op B" and "A op C" both simplify?
207 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
208 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
209 // They do! Return "L op' R" if it simplifies or is already available.
210 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
211 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
212 && L == C && R == B)) {
213 ++NumExpand;
214 return RHS;
216 // Otherwise return "L op' R" if it simplifies.
217 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
218 ++NumExpand;
219 return V;
224 return nullptr;
227 /// Generic simplifications for associative binary operations.
228 /// Returns the simpler value, or null if none was found.
229 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
230 Value *LHS, Value *RHS,
231 const SimplifyQuery &Q,
232 unsigned MaxRecurse) {
233 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
235 // Recursion is always used, so bail out at once if we already hit the limit.
236 if (!MaxRecurse--)
237 return nullptr;
239 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
240 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
242 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
243 if (Op0 && Op0->getOpcode() == Opcode) {
244 Value *A = Op0->getOperand(0);
245 Value *B = Op0->getOperand(1);
246 Value *C = RHS;
248 // Does "B op C" simplify?
249 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
250 // It does! Return "A op V" if it simplifies or is already available.
251 // If V equals B then "A op V" is just the LHS.
252 if (V == B) return LHS;
253 // Otherwise return "A op V" if it simplifies.
254 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
255 ++NumReassoc;
256 return W;
261 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
262 if (Op1 && Op1->getOpcode() == Opcode) {
263 Value *A = LHS;
264 Value *B = Op1->getOperand(0);
265 Value *C = Op1->getOperand(1);
267 // Does "A op B" simplify?
268 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
269 // It does! Return "V op C" if it simplifies or is already available.
270 // If V equals B then "V op C" is just the RHS.
271 if (V == B) return RHS;
272 // Otherwise return "V op C" if it simplifies.
273 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
274 ++NumReassoc;
275 return W;
280 // The remaining transforms require commutativity as well as associativity.
281 if (!Instruction::isCommutative(Opcode))
282 return nullptr;
284 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
285 if (Op0 && Op0->getOpcode() == Opcode) {
286 Value *A = Op0->getOperand(0);
287 Value *B = Op0->getOperand(1);
288 Value *C = RHS;
290 // Does "C op A" simplify?
291 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
292 // It does! Return "V op B" if it simplifies or is already available.
293 // If V equals A then "V op B" is just the LHS.
294 if (V == A) return LHS;
295 // Otherwise return "V op B" if it simplifies.
296 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
297 ++NumReassoc;
298 return W;
303 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
304 if (Op1 && Op1->getOpcode() == Opcode) {
305 Value *A = LHS;
306 Value *B = Op1->getOperand(0);
307 Value *C = Op1->getOperand(1);
309 // Does "C op A" simplify?
310 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
311 // It does! Return "B op V" if it simplifies or is already available.
312 // If V equals C then "B op V" is just the RHS.
313 if (V == C) return RHS;
314 // Otherwise return "B op V" if it simplifies.
315 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
316 ++NumReassoc;
317 return W;
322 return nullptr;
325 /// In the case of a binary operation with a select instruction as an operand,
326 /// try to simplify the binop by seeing whether evaluating it on both branches
327 /// of the select results in the same value. Returns the common value if so,
328 /// otherwise returns null.
329 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
330 Value *RHS, const SimplifyQuery &Q,
331 unsigned MaxRecurse) {
332 // Recursion is always used, so bail out at once if we already hit the limit.
333 if (!MaxRecurse--)
334 return nullptr;
336 SelectInst *SI;
337 if (isa<SelectInst>(LHS)) {
338 SI = cast<SelectInst>(LHS);
339 } else {
340 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
341 SI = cast<SelectInst>(RHS);
344 // Evaluate the BinOp on the true and false branches of the select.
345 Value *TV;
346 Value *FV;
347 if (SI == LHS) {
348 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
349 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
350 } else {
351 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
352 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
355 // If they simplified to the same value, then return the common value.
356 // If they both failed to simplify then return null.
357 if (TV == FV)
358 return TV;
360 // If one branch simplified to undef, return the other one.
361 if (TV && isa<UndefValue>(TV))
362 return FV;
363 if (FV && isa<UndefValue>(FV))
364 return TV;
366 // If applying the operation did not change the true and false select values,
367 // then the result of the binop is the select itself.
368 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
369 return SI;
371 // If one branch simplified and the other did not, and the simplified
372 // value is equal to the unsimplified one, return the simplified value.
373 // For example, select (cond, X, X & Z) & Z -> X & Z.
374 if ((FV && !TV) || (TV && !FV)) {
375 // Check that the simplified value has the form "X op Y" where "op" is the
376 // same as the original operation.
377 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
378 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
379 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
380 // We already know that "op" is the same as for the simplified value. See
381 // if the operands match too. If so, return the simplified value.
382 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
383 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
384 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
385 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
386 Simplified->getOperand(1) == UnsimplifiedRHS)
387 return Simplified;
388 if (Simplified->isCommutative() &&
389 Simplified->getOperand(1) == UnsimplifiedLHS &&
390 Simplified->getOperand(0) == UnsimplifiedRHS)
391 return Simplified;
395 return nullptr;
398 /// In the case of a comparison with a select instruction, try to simplify the
399 /// comparison by seeing whether both branches of the select result in the same
400 /// value. Returns the common value if so, otherwise returns null.
401 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
402 Value *RHS, const SimplifyQuery &Q,
403 unsigned MaxRecurse) {
404 // Recursion is always used, so bail out at once if we already hit the limit.
405 if (!MaxRecurse--)
406 return nullptr;
408 // Make sure the select is on the LHS.
409 if (!isa<SelectInst>(LHS)) {
410 std::swap(LHS, RHS);
411 Pred = CmpInst::getSwappedPredicate(Pred);
413 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
414 SelectInst *SI = cast<SelectInst>(LHS);
415 Value *Cond = SI->getCondition();
416 Value *TV = SI->getTrueValue();
417 Value *FV = SI->getFalseValue();
419 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
420 // Does "cmp TV, RHS" simplify?
421 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
422 if (TCmp == Cond) {
423 // It not only simplified, it simplified to the select condition. Replace
424 // it with 'true'.
425 TCmp = getTrue(Cond->getType());
426 } else if (!TCmp) {
427 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
428 // condition then we can replace it with 'true'. Otherwise give up.
429 if (!isSameCompare(Cond, Pred, TV, RHS))
430 return nullptr;
431 TCmp = getTrue(Cond->getType());
434 // Does "cmp FV, RHS" simplify?
435 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
436 if (FCmp == Cond) {
437 // It not only simplified, it simplified to the select condition. Replace
438 // it with 'false'.
439 FCmp = getFalse(Cond->getType());
440 } else if (!FCmp) {
441 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
442 // condition then we can replace it with 'false'. Otherwise give up.
443 if (!isSameCompare(Cond, Pred, FV, RHS))
444 return nullptr;
445 FCmp = getFalse(Cond->getType());
448 // If both sides simplified to the same value, then use it as the result of
449 // the original comparison.
450 if (TCmp == FCmp)
451 return TCmp;
453 // The remaining cases only make sense if the select condition has the same
454 // type as the result of the comparison, so bail out if this is not so.
455 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
456 return nullptr;
457 // If the false value simplified to false, then the result of the compare
458 // is equal to "Cond && TCmp". This also catches the case when the false
459 // value simplified to false and the true value to true, returning "Cond".
460 if (match(FCmp, m_Zero()))
461 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
462 return V;
463 // If the true value simplified to true, then the result of the compare
464 // is equal to "Cond || FCmp".
465 if (match(TCmp, m_One()))
466 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
467 return V;
468 // Finally, if the false value simplified to true and the true value to
469 // false, then the result of the compare is equal to "!Cond".
470 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
471 if (Value *V =
472 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
473 Q, MaxRecurse))
474 return V;
476 return nullptr;
479 /// In the case of a binary operation with an operand that is a PHI instruction,
480 /// try to simplify the binop by seeing whether evaluating it on the incoming
481 /// phi values yields the same result for every value. If so returns the common
482 /// value, otherwise returns null.
483 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
484 Value *RHS, const SimplifyQuery &Q,
485 unsigned MaxRecurse) {
486 // Recursion is always used, so bail out at once if we already hit the limit.
487 if (!MaxRecurse--)
488 return nullptr;
490 PHINode *PI;
491 if (isa<PHINode>(LHS)) {
492 PI = cast<PHINode>(LHS);
493 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
494 if (!valueDominatesPHI(RHS, PI, Q.DT))
495 return nullptr;
496 } else {
497 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
498 PI = cast<PHINode>(RHS);
499 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
500 if (!valueDominatesPHI(LHS, PI, Q.DT))
501 return nullptr;
504 // Evaluate the BinOp on the incoming phi values.
505 Value *CommonValue = nullptr;
506 for (Value *Incoming : PI->incoming_values()) {
507 // If the incoming value is the phi node itself, it can safely be skipped.
508 if (Incoming == PI) continue;
509 Value *V = PI == LHS ?
510 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
511 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
512 // If the operation failed to simplify, or simplified to a different value
513 // to previously, then give up.
514 if (!V || (CommonValue && V != CommonValue))
515 return nullptr;
516 CommonValue = V;
519 return CommonValue;
522 /// In the case of a comparison with a PHI instruction, try to simplify the
523 /// comparison by seeing whether comparing with all of the incoming phi values
524 /// yields the same result every time. If so returns the common result,
525 /// otherwise returns null.
526 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
527 const SimplifyQuery &Q, unsigned MaxRecurse) {
528 // Recursion is always used, so bail out at once if we already hit the limit.
529 if (!MaxRecurse--)
530 return nullptr;
532 // Make sure the phi is on the LHS.
533 if (!isa<PHINode>(LHS)) {
534 std::swap(LHS, RHS);
535 Pred = CmpInst::getSwappedPredicate(Pred);
537 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
538 PHINode *PI = cast<PHINode>(LHS);
540 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
541 if (!valueDominatesPHI(RHS, PI, Q.DT))
542 return nullptr;
544 // Evaluate the BinOp on the incoming phi values.
545 Value *CommonValue = nullptr;
546 for (Value *Incoming : PI->incoming_values()) {
547 // If the incoming value is the phi node itself, it can safely be skipped.
548 if (Incoming == PI) continue;
549 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
553 return nullptr;
554 CommonValue = V;
557 return CommonValue;
560 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
561 Value *&Op0, Value *&Op1,
562 const SimplifyQuery &Q) {
563 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
564 if (auto *CRHS = dyn_cast<Constant>(Op1))
565 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
567 // Canonicalize the constant to the RHS if this is a commutative operation.
568 if (Instruction::isCommutative(Opcode))
569 std::swap(Op0, Op1);
571 return nullptr;
574 /// Given operands for an Add, see if we can fold the result.
575 /// If not, this returns null.
576 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
577 const SimplifyQuery &Q, unsigned MaxRecurse) {
578 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
579 return C;
581 // X + undef -> undef
582 if (match(Op1, m_Undef()))
583 return Op1;
585 // X + 0 -> X
586 if (match(Op1, m_Zero()))
587 return Op0;
589 // If two operands are negative, return 0.
590 if (isKnownNegation(Op0, Op1))
591 return Constant::getNullValue(Op0->getType());
593 // X + (Y - X) -> Y
594 // (Y - X) + X -> Y
595 // Eg: X + -X -> 0
596 Value *Y = nullptr;
597 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
598 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
599 return Y;
601 // X + ~X -> -1 since ~X = -X-1
602 Type *Ty = Op0->getType();
603 if (match(Op0, m_Not(m_Specific(Op1))) ||
604 match(Op1, m_Not(m_Specific(Op0))))
605 return Constant::getAllOnesValue(Ty);
607 // add nsw/nuw (xor Y, signmask), signmask --> Y
608 // The no-wrapping add guarantees that the top bit will be set by the add.
609 // Therefore, the xor must be clearing the already set sign bit of Y.
610 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
611 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
612 return Y;
614 // add nuw %x, -1 -> -1, because %x can only be 0.
615 if (IsNUW && match(Op1, m_AllOnes()))
616 return Op1; // Which is -1.
618 /// i1 add -> xor.
619 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
620 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
621 return V;
623 // Try some generic simplifications for associative operations.
624 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
625 MaxRecurse))
626 return V;
628 // Threading Add over selects and phi nodes is pointless, so don't bother.
629 // Threading over the select in "A + select(cond, B, C)" means evaluating
630 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
631 // only if B and C are equal. If B and C are equal then (since we assume
632 // that operands have already been simplified) "select(cond, B, C)" should
633 // have been simplified to the common value of B and C already. Analysing
634 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
635 // for threading over phi nodes.
637 return nullptr;
640 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
641 const SimplifyQuery &Query) {
642 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
645 /// Compute the base pointer and cumulative constant offsets for V.
647 /// This strips all constant offsets off of V, leaving it the base pointer, and
648 /// accumulates the total constant offset applied in the returned constant. It
649 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
650 /// no constant offsets applied.
652 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
653 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
654 /// folding.
655 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
656 bool AllowNonInbounds = false) {
657 assert(V->getType()->isPtrOrPtrVectorTy());
659 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
660 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
662 V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
663 // As that strip may trace through `addrspacecast`, need to sext or trunc
664 // the offset calculated.
665 IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
666 Offset = Offset.sextOrTrunc(IntPtrTy->getIntegerBitWidth());
668 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
669 if (V->getType()->isVectorTy())
670 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
671 OffsetIntPtr);
672 return OffsetIntPtr;
675 /// Compute the constant difference between two pointer values.
676 /// If the difference is not a constant, returns zero.
677 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
678 Value *RHS) {
679 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
680 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
682 // If LHS and RHS are not related via constant offsets to the same base
683 // value, there is nothing we can do here.
684 if (LHS != RHS)
685 return nullptr;
687 // Otherwise, the difference of LHS - RHS can be computed as:
688 // LHS - RHS
689 // = (LHSOffset + Base) - (RHSOffset + Base)
690 // = LHSOffset - RHSOffset
691 return ConstantExpr::getSub(LHSOffset, RHSOffset);
694 /// Given operands for a Sub, see if we can fold the result.
695 /// If not, this returns null.
696 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
697 const SimplifyQuery &Q, unsigned MaxRecurse) {
698 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
699 return C;
701 // X - undef -> undef
702 // undef - X -> undef
703 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
704 return UndefValue::get(Op0->getType());
706 // X - 0 -> X
707 if (match(Op1, m_Zero()))
708 return Op0;
710 // X - X -> 0
711 if (Op0 == Op1)
712 return Constant::getNullValue(Op0->getType());
714 // Is this a negation?
715 if (match(Op0, m_Zero())) {
716 // 0 - X -> 0 if the sub is NUW.
717 if (isNUW)
718 return Constant::getNullValue(Op0->getType());
720 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
721 if (Known.Zero.isMaxSignedValue()) {
722 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
723 // Op1 must be 0 because negating the minimum signed value is undefined.
724 if (isNSW)
725 return Constant::getNullValue(Op0->getType());
727 // 0 - X -> X if X is 0 or the minimum signed value.
728 return Op1;
732 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
733 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
734 Value *X = nullptr, *Y = nullptr, *Z = Op1;
735 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
736 // See if "V === Y - Z" simplifies.
737 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
738 // It does! Now see if "X + V" simplifies.
739 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
740 // It does, we successfully reassociated!
741 ++NumReassoc;
742 return W;
744 // See if "V === X - Z" simplifies.
745 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
746 // It does! Now see if "Y + V" simplifies.
747 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
748 // It does, we successfully reassociated!
749 ++NumReassoc;
750 return W;
754 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
755 // For example, X - (X + 1) -> -1
756 X = Op0;
757 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
758 // See if "V === X - Y" simplifies.
759 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
760 // It does! Now see if "V - Z" simplifies.
761 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
762 // It does, we successfully reassociated!
763 ++NumReassoc;
764 return W;
766 // See if "V === X - Z" simplifies.
767 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
768 // It does! Now see if "V - Y" simplifies.
769 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
770 // It does, we successfully reassociated!
771 ++NumReassoc;
772 return W;
776 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
777 // For example, X - (X - Y) -> Y.
778 Z = Op0;
779 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
780 // See if "V === Z - X" simplifies.
781 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
782 // It does! Now see if "V + Y" simplifies.
783 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
784 // It does, we successfully reassociated!
785 ++NumReassoc;
786 return W;
789 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
790 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
791 match(Op1, m_Trunc(m_Value(Y))))
792 if (X->getType() == Y->getType())
793 // See if "V === X - Y" simplifies.
794 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
795 // It does! Now see if "trunc V" simplifies.
796 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
797 Q, MaxRecurse - 1))
798 // It does, return the simplified "trunc V".
799 return W;
801 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
802 if (match(Op0, m_PtrToInt(m_Value(X))) &&
803 match(Op1, m_PtrToInt(m_Value(Y))))
804 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
805 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
807 // i1 sub -> xor.
808 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
809 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
810 return V;
812 // Threading Sub over selects and phi nodes is pointless, so don't bother.
813 // Threading over the select in "A - select(cond, B, C)" means evaluating
814 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
815 // only if B and C are equal. If B and C are equal then (since we assume
816 // that operands have already been simplified) "select(cond, B, C)" should
817 // have been simplified to the common value of B and C already. Analysing
818 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
819 // for threading over phi nodes.
821 return nullptr;
824 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
825 const SimplifyQuery &Q) {
826 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
829 /// Given operands for a Mul, see if we can fold the result.
830 /// If not, this returns null.
831 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
832 unsigned MaxRecurse) {
833 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
834 return C;
836 // X * undef -> 0
837 // X * 0 -> 0
838 if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
839 return Constant::getNullValue(Op0->getType());
841 // X * 1 -> X
842 if (match(Op1, m_One()))
843 return Op0;
845 // (X / Y) * Y -> X if the division is exact.
846 Value *X = nullptr;
847 if (Q.IIQ.UseInstrInfo &&
848 (match(Op0,
849 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
850 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
851 return X;
853 // i1 mul -> and.
854 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
855 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
856 return V;
858 // Try some generic simplifications for associative operations.
859 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
860 MaxRecurse))
861 return V;
863 // Mul distributes over Add. Try some generic simplifications based on this.
864 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
865 Q, MaxRecurse))
866 return V;
868 // If the operation is with the result of a select instruction, check whether
869 // operating on either branch of the select always yields the same value.
870 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
871 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
872 MaxRecurse))
873 return V;
875 // If the operation is with the result of a phi instruction, check whether
876 // operating on all incoming values of the phi always yields the same value.
877 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
878 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
879 MaxRecurse))
880 return V;
882 return nullptr;
885 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
886 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
889 /// Check for common or similar folds of integer division or integer remainder.
890 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
891 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
892 Type *Ty = Op0->getType();
894 // X / undef -> undef
895 // X % undef -> undef
896 if (match(Op1, m_Undef()))
897 return Op1;
899 // X / 0 -> undef
900 // X % 0 -> undef
901 // We don't need to preserve faults!
902 if (match(Op1, m_Zero()))
903 return UndefValue::get(Ty);
905 // If any element of a constant divisor vector is zero or undef, the whole op
906 // is undef.
907 auto *Op1C = dyn_cast<Constant>(Op1);
908 if (Op1C && Ty->isVectorTy()) {
909 unsigned NumElts = Ty->getVectorNumElements();
910 for (unsigned i = 0; i != NumElts; ++i) {
911 Constant *Elt = Op1C->getAggregateElement(i);
912 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
913 return UndefValue::get(Ty);
917 // undef / X -> 0
918 // undef % X -> 0
919 if (match(Op0, m_Undef()))
920 return Constant::getNullValue(Ty);
922 // 0 / X -> 0
923 // 0 % X -> 0
924 if (match(Op0, m_Zero()))
925 return Constant::getNullValue(Op0->getType());
927 // X / X -> 1
928 // X % X -> 0
929 if (Op0 == Op1)
930 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
932 // X / 1 -> X
933 // X % 1 -> 0
934 // If this is a boolean op (single-bit element type), we can't have
935 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
936 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
937 Value *X;
938 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
939 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
940 return IsDiv ? Op0 : Constant::getNullValue(Ty);
942 return nullptr;
945 /// Given a predicate and two operands, return true if the comparison is true.
946 /// This is a helper for div/rem simplification where we return some other value
947 /// when we can prove a relationship between the operands.
948 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
949 const SimplifyQuery &Q, unsigned MaxRecurse) {
950 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
951 Constant *C = dyn_cast_or_null<Constant>(V);
952 return (C && C->isAllOnesValue());
955 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
956 /// to simplify X % Y to X.
957 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
958 unsigned MaxRecurse, bool IsSigned) {
959 // Recursion is always used, so bail out at once if we already hit the limit.
960 if (!MaxRecurse--)
961 return false;
963 if (IsSigned) {
964 // |X| / |Y| --> 0
966 // We require that 1 operand is a simple constant. That could be extended to
967 // 2 variables if we computed the sign bit for each.
969 // Make sure that a constant is not the minimum signed value because taking
970 // the abs() of that is undefined.
971 Type *Ty = X->getType();
972 const APInt *C;
973 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
974 // Is the variable divisor magnitude always greater than the constant
975 // dividend magnitude?
976 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
977 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
978 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
979 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
980 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
981 return true;
983 if (match(Y, m_APInt(C))) {
984 // Special-case: we can't take the abs() of a minimum signed value. If
985 // that's the divisor, then all we have to do is prove that the dividend
986 // is also not the minimum signed value.
987 if (C->isMinSignedValue())
988 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
990 // Is the variable dividend magnitude always less than the constant
991 // divisor magnitude?
992 // |X| < |C| --> X > -abs(C) and X < abs(C)
993 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
994 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
995 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
996 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
997 return true;
999 return false;
1002 // IsSigned == false.
1003 // Is the dividend unsigned less than the divisor?
1004 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1007 /// These are simplifications common to SDiv and UDiv.
1008 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1009 const SimplifyQuery &Q, unsigned MaxRecurse) {
1010 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1011 return C;
1013 if (Value *V = simplifyDivRem(Op0, Op1, true))
1014 return V;
1016 bool IsSigned = Opcode == Instruction::SDiv;
1018 // (X * Y) / Y -> X if the multiplication does not overflow.
1019 Value *X;
1020 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1021 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1022 // If the Mul does not overflow, then we are good to go.
1023 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1024 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
1025 return X;
1026 // If X has the form X = A / Y, then X * Y cannot overflow.
1027 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1028 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1029 return X;
1032 // (X rem Y) / Y -> 0
1033 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1034 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1035 return Constant::getNullValue(Op0->getType());
1037 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1038 ConstantInt *C1, *C2;
1039 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1040 match(Op1, m_ConstantInt(C2))) {
1041 bool Overflow;
1042 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1043 if (Overflow)
1044 return Constant::getNullValue(Op0->getType());
1047 // If the operation is with the result of a select instruction, check whether
1048 // operating on either branch of the select always yields the same value.
1049 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1050 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1051 return V;
1053 // If the operation is with the result of a phi instruction, check whether
1054 // operating on all incoming values of the phi always yields the same value.
1055 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1056 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1057 return V;
1059 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1060 return Constant::getNullValue(Op0->getType());
1062 return nullptr;
1065 /// These are simplifications common to SRem and URem.
1066 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1067 const SimplifyQuery &Q, unsigned MaxRecurse) {
1068 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1069 return C;
1071 if (Value *V = simplifyDivRem(Op0, Op1, false))
1072 return V;
1074 // (X % Y) % Y -> X % Y
1075 if ((Opcode == Instruction::SRem &&
1076 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1077 (Opcode == Instruction::URem &&
1078 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1079 return Op0;
1081 // (X << Y) % X -> 0
1082 if (Q.IIQ.UseInstrInfo &&
1083 ((Opcode == Instruction::SRem &&
1084 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1085 (Opcode == Instruction::URem &&
1086 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1087 return Constant::getNullValue(Op0->getType());
1089 // If the operation is with the result of a select instruction, check whether
1090 // operating on either branch of the select always yields the same value.
1091 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1092 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1093 return V;
1095 // If the operation is with the result of a phi instruction, check whether
1096 // operating on all incoming values of the phi always yields the same value.
1097 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1098 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1099 return V;
1101 // If X / Y == 0, then X % Y == X.
1102 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1103 return Op0;
1105 return nullptr;
1108 /// Given operands for an SDiv, see if we can fold the result.
1109 /// If not, this returns null.
1110 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1111 unsigned MaxRecurse) {
1112 // If two operands are negated and no signed overflow, return -1.
1113 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1114 return Constant::getAllOnesValue(Op0->getType());
1116 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1119 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1120 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1123 /// Given operands for a UDiv, see if we can fold the result.
1124 /// If not, this returns null.
1125 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1126 unsigned MaxRecurse) {
1127 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1130 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1131 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1134 /// Given operands for an SRem, see if we can fold the result.
1135 /// If not, this returns null.
1136 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1137 unsigned MaxRecurse) {
1138 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1139 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1140 Value *X;
1141 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1142 return ConstantInt::getNullValue(Op0->getType());
1144 // If the two operands are negated, return 0.
1145 if (isKnownNegation(Op0, Op1))
1146 return ConstantInt::getNullValue(Op0->getType());
1148 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1151 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1152 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1155 /// Given operands for a URem, see if we can fold the result.
1156 /// If not, this returns null.
1157 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1158 unsigned MaxRecurse) {
1159 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1162 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1163 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1166 /// Returns true if a shift by \c Amount always yields undef.
1167 static bool isUndefShift(Value *Amount) {
1168 Constant *C = dyn_cast<Constant>(Amount);
1169 if (!C)
1170 return false;
1172 // X shift by undef -> undef because it may shift by the bitwidth.
1173 if (isa<UndefValue>(C))
1174 return true;
1176 // Shifting by the bitwidth or more is undefined.
1177 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1178 if (CI->getValue().getLimitedValue() >=
1179 CI->getType()->getScalarSizeInBits())
1180 return true;
1182 // If all lanes of a vector shift are undefined the whole shift is.
1183 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1184 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1185 if (!isUndefShift(C->getAggregateElement(I)))
1186 return false;
1187 return true;
1190 return false;
1193 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1194 /// If not, this returns null.
1195 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1196 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
1197 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1198 return C;
1200 // 0 shift by X -> 0
1201 if (match(Op0, m_Zero()))
1202 return Constant::getNullValue(Op0->getType());
1204 // X shift by 0 -> X
1205 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1206 // would be poison.
1207 Value *X;
1208 if (match(Op1, m_Zero()) ||
1209 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1210 return Op0;
1212 // Fold undefined shifts.
1213 if (isUndefShift(Op1))
1214 return UndefValue::get(Op0->getType());
1216 // If the operation is with the result of a select instruction, check whether
1217 // operating on either branch of the select always yields the same value.
1218 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1219 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1220 return V;
1222 // If the operation is with the result of a phi instruction, check whether
1223 // operating on all incoming values of the phi always yields the same value.
1224 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1225 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1226 return V;
1228 // If any bits in the shift amount make that value greater than or equal to
1229 // the number of bits in the type, the shift is undefined.
1230 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1231 if (Known.One.getLimitedValue() >= Known.getBitWidth())
1232 return UndefValue::get(Op0->getType());
1234 // If all valid bits in the shift amount are known zero, the first operand is
1235 // unchanged.
1236 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
1237 if (Known.countMinTrailingZeros() >= NumValidShiftBits)
1238 return Op0;
1240 return nullptr;
1243 /// Given operands for an Shl, LShr or AShr, see if we can
1244 /// fold the result. If not, this returns null.
1245 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1246 Value *Op1, bool isExact, const SimplifyQuery &Q,
1247 unsigned MaxRecurse) {
1248 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1249 return V;
1251 // X >> X -> 0
1252 if (Op0 == Op1)
1253 return Constant::getNullValue(Op0->getType());
1255 // undef >> X -> 0
1256 // undef >> X -> undef (if it's exact)
1257 if (match(Op0, m_Undef()))
1258 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1260 // The low bit cannot be shifted out of an exact shift if it is set.
1261 if (isExact) {
1262 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1263 if (Op0Known.One[0])
1264 return Op0;
1267 return nullptr;
1270 /// Given operands for an Shl, see if we can fold the result.
1271 /// If not, this returns null.
1272 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1273 const SimplifyQuery &Q, unsigned MaxRecurse) {
1274 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1275 return V;
1277 // undef << X -> 0
1278 // undef << X -> undef if (if it's NSW/NUW)
1279 if (match(Op0, m_Undef()))
1280 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1282 // (X >> A) << A -> X
1283 Value *X;
1284 if (Q.IIQ.UseInstrInfo &&
1285 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1286 return X;
1288 // shl nuw i8 C, %x -> C iff C has sign bit set.
1289 if (isNUW && match(Op0, m_Negative()))
1290 return Op0;
1291 // NOTE: could use computeKnownBits() / LazyValueInfo,
1292 // but the cost-benefit analysis suggests it isn't worth it.
1294 return nullptr;
1297 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1298 const SimplifyQuery &Q) {
1299 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1302 /// Given operands for an LShr, see if we can fold the result.
1303 /// If not, this returns null.
1304 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1305 const SimplifyQuery &Q, unsigned MaxRecurse) {
1306 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1307 MaxRecurse))
1308 return V;
1310 // (X << A) >> A -> X
1311 Value *X;
1312 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1313 return X;
1315 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1316 // We can return X as we do in the above case since OR alters no bits in X.
1317 // SimplifyDemandedBits in InstCombine can do more general optimization for
1318 // bit manipulation. This pattern aims to provide opportunities for other
1319 // optimizers by supporting a simple but common case in InstSimplify.
1320 Value *Y;
1321 const APInt *ShRAmt, *ShLAmt;
1322 if (match(Op1, m_APInt(ShRAmt)) &&
1323 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1324 *ShRAmt == *ShLAmt) {
1325 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1326 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1327 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1328 if (ShRAmt->uge(EffWidthY))
1329 return X;
1332 return nullptr;
1335 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1336 const SimplifyQuery &Q) {
1337 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1340 /// Given operands for an AShr, see if we can fold the result.
1341 /// If not, this returns null.
1342 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1343 const SimplifyQuery &Q, unsigned MaxRecurse) {
1344 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1345 MaxRecurse))
1346 return V;
1348 // all ones >>a X -> -1
1349 // Do not return Op0 because it may contain undef elements if it's a vector.
1350 if (match(Op0, m_AllOnes()))
1351 return Constant::getAllOnesValue(Op0->getType());
1353 // (X << A) >> A -> X
1354 Value *X;
1355 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1356 return X;
1358 // Arithmetic shifting an all-sign-bit value is a no-op.
1359 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1360 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1361 return Op0;
1363 return nullptr;
1366 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1367 const SimplifyQuery &Q) {
1368 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1371 /// Commuted variants are assumed to be handled by calling this function again
1372 /// with the parameters swapped.
1373 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1374 ICmpInst *UnsignedICmp, bool IsAnd) {
1375 Value *X, *Y;
1377 ICmpInst::Predicate EqPred;
1378 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1379 !ICmpInst::isEquality(EqPred))
1380 return nullptr;
1382 ICmpInst::Predicate UnsignedPred;
1383 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1384 ICmpInst::isUnsigned(UnsignedPred))
1386 else if (match(UnsignedICmp,
1387 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1388 ICmpInst::isUnsigned(UnsignedPred))
1389 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1390 else
1391 return nullptr;
1393 // X < Y && Y != 0 --> X < Y
1394 // X < Y || Y != 0 --> Y != 0
1395 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1396 return IsAnd ? UnsignedICmp : ZeroICmp;
1398 // X >= Y || Y != 0 --> true
1399 // X >= Y || Y == 0 --> X >= Y
1400 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1401 if (EqPred == ICmpInst::ICMP_NE)
1402 return getTrue(UnsignedICmp->getType());
1403 return UnsignedICmp;
1406 // X < Y && Y == 0 --> false
1407 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1408 IsAnd)
1409 return getFalse(UnsignedICmp->getType());
1411 return nullptr;
1414 /// Commuted variants are assumed to be handled by calling this function again
1415 /// with the parameters swapped.
1416 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1417 ICmpInst::Predicate Pred0, Pred1;
1418 Value *A ,*B;
1419 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1420 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1421 return nullptr;
1423 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1424 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1425 // can eliminate Op1 from this 'and'.
1426 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1427 return Op0;
1429 // Check for any combination of predicates that are guaranteed to be disjoint.
1430 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1431 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1432 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1433 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1434 return getFalse(Op0->getType());
1436 return nullptr;
1439 /// Commuted variants are assumed to be handled by calling this function again
1440 /// with the parameters swapped.
1441 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1442 ICmpInst::Predicate Pred0, Pred1;
1443 Value *A ,*B;
1444 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1445 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1446 return nullptr;
1448 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1449 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1450 // can eliminate Op0 from this 'or'.
1451 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1452 return Op1;
1454 // Check for any combination of predicates that cover the entire range of
1455 // possibilities.
1456 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1457 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1458 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1459 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1460 return getTrue(Op0->getType());
1462 return nullptr;
1465 /// Test if a pair of compares with a shared operand and 2 constants has an
1466 /// empty set intersection, full set union, or if one compare is a superset of
1467 /// the other.
1468 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1469 bool IsAnd) {
1470 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1471 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1472 return nullptr;
1474 const APInt *C0, *C1;
1475 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1476 !match(Cmp1->getOperand(1), m_APInt(C1)))
1477 return nullptr;
1479 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1480 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1482 // For and-of-compares, check if the intersection is empty:
1483 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1484 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1485 return getFalse(Cmp0->getType());
1487 // For or-of-compares, check if the union is full:
1488 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1489 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1490 return getTrue(Cmp0->getType());
1492 // Is one range a superset of the other?
1493 // If this is and-of-compares, take the smaller set:
1494 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1495 // If this is or-of-compares, take the larger set:
1496 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1497 if (Range0.contains(Range1))
1498 return IsAnd ? Cmp1 : Cmp0;
1499 if (Range1.contains(Range0))
1500 return IsAnd ? Cmp0 : Cmp1;
1502 return nullptr;
1505 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1506 bool IsAnd) {
1507 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1508 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1509 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1510 return nullptr;
1512 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1513 return nullptr;
1515 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1516 Value *X = Cmp0->getOperand(0);
1517 Value *Y = Cmp1->getOperand(0);
1519 // If one of the compares is a masked version of a (not) null check, then
1520 // that compare implies the other, so we eliminate the other. Optionally, look
1521 // through a pointer-to-int cast to match a null check of a pointer type.
1523 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1524 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1525 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1526 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1527 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1528 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1529 return Cmp1;
1531 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1532 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1533 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1534 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1535 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1536 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1537 return Cmp0;
1539 return nullptr;
1542 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1543 const InstrInfoQuery &IIQ) {
1544 // (icmp (add V, C0), C1) & (icmp V, C0)
1545 ICmpInst::Predicate Pred0, Pred1;
1546 const APInt *C0, *C1;
1547 Value *V;
1548 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1549 return nullptr;
1551 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1552 return nullptr;
1554 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1555 if (AddInst->getOperand(1) != Op1->getOperand(1))
1556 return nullptr;
1558 Type *ITy = Op0->getType();
1559 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1560 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1562 const APInt Delta = *C1 - *C0;
1563 if (C0->isStrictlyPositive()) {
1564 if (Delta == 2) {
1565 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1566 return getFalse(ITy);
1567 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1568 return getFalse(ITy);
1570 if (Delta == 1) {
1571 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1572 return getFalse(ITy);
1573 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1574 return getFalse(ITy);
1577 if (C0->getBoolValue() && isNUW) {
1578 if (Delta == 2)
1579 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1580 return getFalse(ITy);
1581 if (Delta == 1)
1582 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1583 return getFalse(ITy);
1586 return nullptr;
1589 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1590 const InstrInfoQuery &IIQ) {
1591 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1592 return X;
1593 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
1594 return X;
1596 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1597 return X;
1598 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1599 return X;
1601 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1602 return X;
1604 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1605 return X;
1607 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ))
1608 return X;
1609 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, IIQ))
1610 return X;
1612 return nullptr;
1615 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1616 const InstrInfoQuery &IIQ) {
1617 // (icmp (add V, C0), C1) | (icmp V, C0)
1618 ICmpInst::Predicate Pred0, Pred1;
1619 const APInt *C0, *C1;
1620 Value *V;
1621 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1622 return nullptr;
1624 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1625 return nullptr;
1627 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1628 if (AddInst->getOperand(1) != Op1->getOperand(1))
1629 return nullptr;
1631 Type *ITy = Op0->getType();
1632 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1633 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1635 const APInt Delta = *C1 - *C0;
1636 if (C0->isStrictlyPositive()) {
1637 if (Delta == 2) {
1638 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1639 return getTrue(ITy);
1640 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1641 return getTrue(ITy);
1643 if (Delta == 1) {
1644 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1645 return getTrue(ITy);
1646 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1647 return getTrue(ITy);
1650 if (C0->getBoolValue() && isNUW) {
1651 if (Delta == 2)
1652 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1653 return getTrue(ITy);
1654 if (Delta == 1)
1655 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1656 return getTrue(ITy);
1659 return nullptr;
1662 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1663 const InstrInfoQuery &IIQ) {
1664 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1665 return X;
1666 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1667 return X;
1669 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1670 return X;
1671 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1672 return X;
1674 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1675 return X;
1677 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1678 return X;
1680 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ))
1681 return X;
1682 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, IIQ))
1683 return X;
1685 return nullptr;
1688 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1689 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1690 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1691 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1692 if (LHS0->getType() != RHS0->getType())
1693 return nullptr;
1695 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1696 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1697 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1698 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1699 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1700 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1701 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1702 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1703 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1704 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1705 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1706 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1707 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1708 return RHS;
1710 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1711 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1712 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1713 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1714 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1715 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1716 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1717 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1718 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1719 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1720 return LHS;
1723 return nullptr;
1726 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
1727 Value *Op0, Value *Op1, bool IsAnd) {
1728 // Look through casts of the 'and' operands to find compares.
1729 auto *Cast0 = dyn_cast<CastInst>(Op0);
1730 auto *Cast1 = dyn_cast<CastInst>(Op1);
1731 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1732 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1733 Op0 = Cast0->getOperand(0);
1734 Op1 = Cast1->getOperand(0);
1737 Value *V = nullptr;
1738 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1739 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1740 if (ICmp0 && ICmp1)
1741 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q.IIQ)
1742 : simplifyOrOfICmps(ICmp0, ICmp1, Q.IIQ);
1744 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1745 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1746 if (FCmp0 && FCmp1)
1747 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
1749 if (!V)
1750 return nullptr;
1751 if (!Cast0)
1752 return V;
1754 // If we looked through casts, we can only handle a constant simplification
1755 // because we are not allowed to create a cast instruction here.
1756 if (auto *C = dyn_cast<Constant>(V))
1757 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1759 return nullptr;
1762 /// Given operands for an And, see if we can fold the result.
1763 /// If not, this returns null.
1764 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1765 unsigned MaxRecurse) {
1766 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1767 return C;
1769 // X & undef -> 0
1770 if (match(Op1, m_Undef()))
1771 return Constant::getNullValue(Op0->getType());
1773 // X & X = X
1774 if (Op0 == Op1)
1775 return Op0;
1777 // X & 0 = 0
1778 if (match(Op1, m_Zero()))
1779 return Constant::getNullValue(Op0->getType());
1781 // X & -1 = X
1782 if (match(Op1, m_AllOnes()))
1783 return Op0;
1785 // A & ~A = ~A & A = 0
1786 if (match(Op0, m_Not(m_Specific(Op1))) ||
1787 match(Op1, m_Not(m_Specific(Op0))))
1788 return Constant::getNullValue(Op0->getType());
1790 // (A | ?) & A = A
1791 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1792 return Op1;
1794 // A & (A | ?) = A
1795 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
1796 return Op0;
1798 // A mask that only clears known zeros of a shifted value is a no-op.
1799 Value *X;
1800 const APInt *Mask;
1801 const APInt *ShAmt;
1802 if (match(Op1, m_APInt(Mask))) {
1803 // If all bits in the inverted and shifted mask are clear:
1804 // and (shl X, ShAmt), Mask --> shl X, ShAmt
1805 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1806 (~(*Mask)).lshr(*ShAmt).isNullValue())
1807 return Op0;
1809 // If all bits in the inverted and shifted mask are clear:
1810 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1811 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1812 (~(*Mask)).shl(*ShAmt).isNullValue())
1813 return Op0;
1816 // A & (-A) = A if A is a power of two or zero.
1817 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1818 match(Op1, m_Neg(m_Specific(Op0)))) {
1819 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1820 Q.DT))
1821 return Op0;
1822 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1823 Q.DT))
1824 return Op1;
1827 // This is a similar pattern used for checking if a value is a power-of-2:
1828 // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
1829 // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
1830 if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
1831 isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1832 return Constant::getNullValue(Op1->getType());
1833 if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
1834 isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1835 return Constant::getNullValue(Op0->getType());
1837 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
1838 return V;
1840 // Try some generic simplifications for associative operations.
1841 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1842 MaxRecurse))
1843 return V;
1845 // And distributes over Or. Try some generic simplifications based on this.
1846 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1847 Q, MaxRecurse))
1848 return V;
1850 // And distributes over Xor. Try some generic simplifications based on this.
1851 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1852 Q, MaxRecurse))
1853 return V;
1855 // If the operation is with the result of a select instruction, check whether
1856 // operating on either branch of the select always yields the same value.
1857 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1858 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1859 MaxRecurse))
1860 return V;
1862 // If the operation is with the result of a phi instruction, check whether
1863 // operating on all incoming values of the phi always yields the same value.
1864 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1865 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1866 MaxRecurse))
1867 return V;
1869 // Assuming the effective width of Y is not larger than A, i.e. all bits
1870 // from X and Y are disjoint in (X << A) | Y,
1871 // if the mask of this AND op covers all bits of X or Y, while it covers
1872 // no bits from the other, we can bypass this AND op. E.g.,
1873 // ((X << A) | Y) & Mask -> Y,
1874 // if Mask = ((1 << effective_width_of(Y)) - 1)
1875 // ((X << A) | Y) & Mask -> X << A,
1876 // if Mask = ((1 << effective_width_of(X)) - 1) << A
1877 // SimplifyDemandedBits in InstCombine can optimize the general case.
1878 // This pattern aims to help other passes for a common case.
1879 Value *Y, *XShifted;
1880 if (match(Op1, m_APInt(Mask)) &&
1881 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
1882 m_Value(XShifted)),
1883 m_Value(Y)))) {
1884 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1885 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
1886 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1887 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1888 if (EffWidthY <= ShftCnt) {
1889 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
1890 Q.DT);
1891 const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
1892 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
1893 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
1894 // If the mask is extracting all bits from X or Y as is, we can skip
1895 // this AND op.
1896 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
1897 return Y;
1898 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
1899 return XShifted;
1903 return nullptr;
1906 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1907 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1910 /// Given operands for an Or, see if we can fold the result.
1911 /// If not, this returns null.
1912 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1913 unsigned MaxRecurse) {
1914 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1915 return C;
1917 // X | undef -> -1
1918 // X | -1 = -1
1919 // Do not return Op1 because it may contain undef elements if it's a vector.
1920 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
1921 return Constant::getAllOnesValue(Op0->getType());
1923 // X | X = X
1924 // X | 0 = X
1925 if (Op0 == Op1 || match(Op1, m_Zero()))
1926 return Op0;
1928 // A | ~A = ~A | A = -1
1929 if (match(Op0, m_Not(m_Specific(Op1))) ||
1930 match(Op1, m_Not(m_Specific(Op0))))
1931 return Constant::getAllOnesValue(Op0->getType());
1933 // (A & ?) | A = A
1934 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
1935 return Op1;
1937 // A | (A & ?) = A
1938 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
1939 return Op0;
1941 // ~(A & ?) | A = -1
1942 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1943 return Constant::getAllOnesValue(Op1->getType());
1945 // A | ~(A & ?) = -1
1946 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1947 return Constant::getAllOnesValue(Op0->getType());
1949 Value *A, *B;
1950 // (A & ~B) | (A ^ B) -> (A ^ B)
1951 // (~B & A) | (A ^ B) -> (A ^ B)
1952 // (A & ~B) | (B ^ A) -> (B ^ A)
1953 // (~B & A) | (B ^ A) -> (B ^ A)
1954 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1955 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1956 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1957 return Op1;
1959 // Commute the 'or' operands.
1960 // (A ^ B) | (A & ~B) -> (A ^ B)
1961 // (A ^ B) | (~B & A) -> (A ^ B)
1962 // (B ^ A) | (A & ~B) -> (B ^ A)
1963 // (B ^ A) | (~B & A) -> (B ^ A)
1964 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1965 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1966 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1967 return Op0;
1969 // (A & B) | (~A ^ B) -> (~A ^ B)
1970 // (B & A) | (~A ^ B) -> (~A ^ B)
1971 // (A & B) | (B ^ ~A) -> (B ^ ~A)
1972 // (B & A) | (B ^ ~A) -> (B ^ ~A)
1973 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1974 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1975 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1976 return Op1;
1978 // (~A ^ B) | (A & B) -> (~A ^ B)
1979 // (~A ^ B) | (B & A) -> (~A ^ B)
1980 // (B ^ ~A) | (A & B) -> (B ^ ~A)
1981 // (B ^ ~A) | (B & A) -> (B ^ ~A)
1982 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1983 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1984 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1985 return Op0;
1987 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
1988 return V;
1990 // Try some generic simplifications for associative operations.
1991 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1992 MaxRecurse))
1993 return V;
1995 // Or distributes over And. Try some generic simplifications based on this.
1996 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1997 MaxRecurse))
1998 return V;
2000 // If the operation is with the result of a select instruction, check whether
2001 // operating on either branch of the select always yields the same value.
2002 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
2003 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2004 MaxRecurse))
2005 return V;
2007 // (A & C1)|(B & C2)
2008 const APInt *C1, *C2;
2009 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2010 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2011 if (*C1 == ~*C2) {
2012 // (A & C1)|(B & C2)
2013 // If we have: ((V + N) & C1) | (V & C2)
2014 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2015 // replace with V+N.
2016 Value *N;
2017 if (C2->isMask() && // C2 == 0+1+
2018 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2019 // Add commutes, try both ways.
2020 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2021 return A;
2023 // Or commutes, try both ways.
2024 if (C1->isMask() &&
2025 match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2026 // Add commutes, try both ways.
2027 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2028 return B;
2033 // If the operation is with the result of a phi instruction, check whether
2034 // operating on all incoming values of the phi always yields the same value.
2035 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2036 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2037 return V;
2039 return nullptr;
2042 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2043 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2046 /// Given operands for a Xor, see if we can fold the result.
2047 /// If not, this returns null.
2048 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2049 unsigned MaxRecurse) {
2050 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2051 return C;
2053 // A ^ undef -> undef
2054 if (match(Op1, m_Undef()))
2055 return Op1;
2057 // A ^ 0 = A
2058 if (match(Op1, m_Zero()))
2059 return Op0;
2061 // A ^ A = 0
2062 if (Op0 == Op1)
2063 return Constant::getNullValue(Op0->getType());
2065 // A ^ ~A = ~A ^ A = -1
2066 if (match(Op0, m_Not(m_Specific(Op1))) ||
2067 match(Op1, m_Not(m_Specific(Op0))))
2068 return Constant::getAllOnesValue(Op0->getType());
2070 // Try some generic simplifications for associative operations.
2071 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2072 MaxRecurse))
2073 return V;
2075 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2076 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2077 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2078 // only if B and C are equal. If B and C are equal then (since we assume
2079 // that operands have already been simplified) "select(cond, B, C)" should
2080 // have been simplified to the common value of B and C already. Analysing
2081 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2082 // for threading over phi nodes.
2084 return nullptr;
2087 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2088 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2092 static Type *GetCompareTy(Value *Op) {
2093 return CmpInst::makeCmpResultType(Op->getType());
2096 /// Rummage around inside V looking for something equivalent to the comparison
2097 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2098 /// Helper function for analyzing max/min idioms.
2099 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2100 Value *LHS, Value *RHS) {
2101 SelectInst *SI = dyn_cast<SelectInst>(V);
2102 if (!SI)
2103 return nullptr;
2104 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2105 if (!Cmp)
2106 return nullptr;
2107 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2108 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2109 return Cmp;
2110 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2111 LHS == CmpRHS && RHS == CmpLHS)
2112 return Cmp;
2113 return nullptr;
2116 // A significant optimization not implemented here is assuming that alloca
2117 // addresses are not equal to incoming argument values. They don't *alias*,
2118 // as we say, but that doesn't mean they aren't equal, so we take a
2119 // conservative approach.
2121 // This is inspired in part by C++11 5.10p1:
2122 // "Two pointers of the same type compare equal if and only if they are both
2123 // null, both point to the same function, or both represent the same
2124 // address."
2126 // This is pretty permissive.
2128 // It's also partly due to C11 6.5.9p6:
2129 // "Two pointers compare equal if and only if both are null pointers, both are
2130 // pointers to the same object (including a pointer to an object and a
2131 // subobject at its beginning) or function, both are pointers to one past the
2132 // last element of the same array object, or one is a pointer to one past the
2133 // end of one array object and the other is a pointer to the start of a
2134 // different array object that happens to immediately follow the first array
2135 // object in the address space.)
2137 // C11's version is more restrictive, however there's no reason why an argument
2138 // couldn't be a one-past-the-end value for a stack object in the caller and be
2139 // equal to the beginning of a stack object in the callee.
2141 // If the C and C++ standards are ever made sufficiently restrictive in this
2142 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2143 // this optimization.
2144 static Constant *
2145 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2146 const DominatorTree *DT, CmpInst::Predicate Pred,
2147 AssumptionCache *AC, const Instruction *CxtI,
2148 const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
2149 // First, skip past any trivial no-ops.
2150 LHS = LHS->stripPointerCasts();
2151 RHS = RHS->stripPointerCasts();
2153 // A non-null pointer is not equal to a null pointer.
2154 if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2155 IIQ.UseInstrInfo) &&
2156 isa<ConstantPointerNull>(RHS) &&
2157 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2158 return ConstantInt::get(GetCompareTy(LHS),
2159 !CmpInst::isTrueWhenEqual(Pred));
2161 // We can only fold certain predicates on pointer comparisons.
2162 switch (Pred) {
2163 default:
2164 return nullptr;
2166 // Equality comaprisons are easy to fold.
2167 case CmpInst::ICMP_EQ:
2168 case CmpInst::ICMP_NE:
2169 break;
2171 // We can only handle unsigned relational comparisons because 'inbounds' on
2172 // a GEP only protects against unsigned wrapping.
2173 case CmpInst::ICMP_UGT:
2174 case CmpInst::ICMP_UGE:
2175 case CmpInst::ICMP_ULT:
2176 case CmpInst::ICMP_ULE:
2177 // However, we have to switch them to their signed variants to handle
2178 // negative indices from the base pointer.
2179 Pred = ICmpInst::getSignedPredicate(Pred);
2180 break;
2183 // Strip off any constant offsets so that we can reason about them.
2184 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2185 // here and compare base addresses like AliasAnalysis does, however there are
2186 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2187 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2188 // doesn't need to guarantee pointer inequality when it says NoAlias.
2189 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2190 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2192 // If LHS and RHS are related via constant offsets to the same base
2193 // value, we can replace it with an icmp which just compares the offsets.
2194 if (LHS == RHS)
2195 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2197 // Various optimizations for (in)equality comparisons.
2198 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2199 // Different non-empty allocations that exist at the same time have
2200 // different addresses (if the program can tell). Global variables always
2201 // exist, so they always exist during the lifetime of each other and all
2202 // allocas. Two different allocas usually have different addresses...
2204 // However, if there's an @llvm.stackrestore dynamically in between two
2205 // allocas, they may have the same address. It's tempting to reduce the
2206 // scope of the problem by only looking at *static* allocas here. That would
2207 // cover the majority of allocas while significantly reducing the likelihood
2208 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2209 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2210 // an entry block. Also, if we have a block that's not attached to a
2211 // function, we can't tell if it's "static" under the current definition.
2212 // Theoretically, this problem could be fixed by creating a new kind of
2213 // instruction kind specifically for static allocas. Such a new instruction
2214 // could be required to be at the top of the entry block, thus preventing it
2215 // from being subject to a @llvm.stackrestore. Instcombine could even
2216 // convert regular allocas into these special allocas. It'd be nifty.
2217 // However, until then, this problem remains open.
2219 // So, we'll assume that two non-empty allocas have different addresses
2220 // for now.
2222 // With all that, if the offsets are within the bounds of their allocations
2223 // (and not one-past-the-end! so we can't use inbounds!), and their
2224 // allocations aren't the same, the pointers are not equal.
2226 // Note that it's not necessary to check for LHS being a global variable
2227 // address, due to canonicalization and constant folding.
2228 if (isa<AllocaInst>(LHS) &&
2229 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2230 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2231 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2232 uint64_t LHSSize, RHSSize;
2233 ObjectSizeOpts Opts;
2234 Opts.NullIsUnknownSize =
2235 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
2236 if (LHSOffsetCI && RHSOffsetCI &&
2237 getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2238 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2239 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2240 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2241 if (!LHSOffsetValue.isNegative() &&
2242 !RHSOffsetValue.isNegative() &&
2243 LHSOffsetValue.ult(LHSSize) &&
2244 RHSOffsetValue.ult(RHSSize)) {
2245 return ConstantInt::get(GetCompareTy(LHS),
2246 !CmpInst::isTrueWhenEqual(Pred));
2250 // Repeat the above check but this time without depending on DataLayout
2251 // or being able to compute a precise size.
2252 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2253 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2254 LHSOffset->isNullValue() &&
2255 RHSOffset->isNullValue())
2256 return ConstantInt::get(GetCompareTy(LHS),
2257 !CmpInst::isTrueWhenEqual(Pred));
2260 // Even if an non-inbounds GEP occurs along the path we can still optimize
2261 // equality comparisons concerning the result. We avoid walking the whole
2262 // chain again by starting where the last calls to
2263 // stripAndComputeConstantOffsets left off and accumulate the offsets.
2264 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2265 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2266 if (LHS == RHS)
2267 return ConstantExpr::getICmp(Pred,
2268 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2269 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2271 // If one side of the equality comparison must come from a noalias call
2272 // (meaning a system memory allocation function), and the other side must
2273 // come from a pointer that cannot overlap with dynamically-allocated
2274 // memory within the lifetime of the current function (allocas, byval
2275 // arguments, globals), then determine the comparison result here.
2276 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2277 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2278 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2280 // Is the set of underlying objects all noalias calls?
2281 auto IsNAC = [](ArrayRef<const Value *> Objects) {
2282 return all_of(Objects, isNoAliasCall);
2285 // Is the set of underlying objects all things which must be disjoint from
2286 // noalias calls. For allocas, we consider only static ones (dynamic
2287 // allocas might be transformed into calls to malloc not simultaneously
2288 // live with the compared-to allocation). For globals, we exclude symbols
2289 // that might be resolve lazily to symbols in another dynamically-loaded
2290 // library (and, thus, could be malloc'ed by the implementation).
2291 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2292 return all_of(Objects, [](const Value *V) {
2293 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2294 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2295 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2296 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2297 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2298 !GV->isThreadLocal();
2299 if (const Argument *A = dyn_cast<Argument>(V))
2300 return A->hasByValAttr();
2301 return false;
2305 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2306 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2307 return ConstantInt::get(GetCompareTy(LHS),
2308 !CmpInst::isTrueWhenEqual(Pred));
2310 // Fold comparisons for non-escaping pointer even if the allocation call
2311 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2312 // dynamic allocation call could be either of the operands.
2313 Value *MI = nullptr;
2314 if (isAllocLikeFn(LHS, TLI) &&
2315 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2316 MI = LHS;
2317 else if (isAllocLikeFn(RHS, TLI) &&
2318 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2319 MI = RHS;
2320 // FIXME: We should also fold the compare when the pointer escapes, but the
2321 // compare dominates the pointer escape
2322 if (MI && !PointerMayBeCaptured(MI, true, true))
2323 return ConstantInt::get(GetCompareTy(LHS),
2324 CmpInst::isFalseWhenEqual(Pred));
2327 // Otherwise, fail.
2328 return nullptr;
2331 /// Fold an icmp when its operands have i1 scalar type.
2332 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2333 Value *RHS, const SimplifyQuery &Q) {
2334 Type *ITy = GetCompareTy(LHS); // The return type.
2335 Type *OpTy = LHS->getType(); // The operand type.
2336 if (!OpTy->isIntOrIntVectorTy(1))
2337 return nullptr;
2339 // A boolean compared to true/false can be simplified in 14 out of the 20
2340 // (10 predicates * 2 constants) possible combinations. Cases not handled here
2341 // require a 'not' of the LHS, so those must be transformed in InstCombine.
2342 if (match(RHS, m_Zero())) {
2343 switch (Pred) {
2344 case CmpInst::ICMP_NE: // X != 0 -> X
2345 case CmpInst::ICMP_UGT: // X >u 0 -> X
2346 case CmpInst::ICMP_SLT: // X <s 0 -> X
2347 return LHS;
2349 case CmpInst::ICMP_ULT: // X <u 0 -> false
2350 case CmpInst::ICMP_SGT: // X >s 0 -> false
2351 return getFalse(ITy);
2353 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2354 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2355 return getTrue(ITy);
2357 default: break;
2359 } else if (match(RHS, m_One())) {
2360 switch (Pred) {
2361 case CmpInst::ICMP_EQ: // X == 1 -> X
2362 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2363 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2364 return LHS;
2366 case CmpInst::ICMP_UGT: // X >u 1 -> false
2367 case CmpInst::ICMP_SLT: // X <s -1 -> false
2368 return getFalse(ITy);
2370 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2371 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2372 return getTrue(ITy);
2374 default: break;
2378 switch (Pred) {
2379 default:
2380 break;
2381 case ICmpInst::ICMP_UGE:
2382 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2383 return getTrue(ITy);
2384 break;
2385 case ICmpInst::ICMP_SGE:
2386 /// For signed comparison, the values for an i1 are 0 and -1
2387 /// respectively. This maps into a truth table of:
2388 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2389 /// 0 | 0 | 1 (0 >= 0) | 1
2390 /// 0 | 1 | 1 (0 >= -1) | 1
2391 /// 1 | 0 | 0 (-1 >= 0) | 0
2392 /// 1 | 1 | 1 (-1 >= -1) | 1
2393 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2394 return getTrue(ITy);
2395 break;
2396 case ICmpInst::ICMP_ULE:
2397 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2398 return getTrue(ITy);
2399 break;
2402 return nullptr;
2405 /// Try hard to fold icmp with zero RHS because this is a common case.
2406 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2407 Value *RHS, const SimplifyQuery &Q) {
2408 if (!match(RHS, m_Zero()))
2409 return nullptr;
2411 Type *ITy = GetCompareTy(LHS); // The return type.
2412 switch (Pred) {
2413 default:
2414 llvm_unreachable("Unknown ICmp predicate!");
2415 case ICmpInst::ICMP_ULT:
2416 return getFalse(ITy);
2417 case ICmpInst::ICMP_UGE:
2418 return getTrue(ITy);
2419 case ICmpInst::ICMP_EQ:
2420 case ICmpInst::ICMP_ULE:
2421 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2422 return getFalse(ITy);
2423 break;
2424 case ICmpInst::ICMP_NE:
2425 case ICmpInst::ICMP_UGT:
2426 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2427 return getTrue(ITy);
2428 break;
2429 case ICmpInst::ICMP_SLT: {
2430 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2431 if (LHSKnown.isNegative())
2432 return getTrue(ITy);
2433 if (LHSKnown.isNonNegative())
2434 return getFalse(ITy);
2435 break;
2437 case ICmpInst::ICMP_SLE: {
2438 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2439 if (LHSKnown.isNegative())
2440 return getTrue(ITy);
2441 if (LHSKnown.isNonNegative() &&
2442 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2443 return getFalse(ITy);
2444 break;
2446 case ICmpInst::ICMP_SGE: {
2447 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2448 if (LHSKnown.isNegative())
2449 return getFalse(ITy);
2450 if (LHSKnown.isNonNegative())
2451 return getTrue(ITy);
2452 break;
2454 case ICmpInst::ICMP_SGT: {
2455 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2456 if (LHSKnown.isNegative())
2457 return getFalse(ITy);
2458 if (LHSKnown.isNonNegative() &&
2459 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2460 return getTrue(ITy);
2461 break;
2465 return nullptr;
2468 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2469 Value *RHS, const InstrInfoQuery &IIQ) {
2470 Type *ITy = GetCompareTy(RHS); // The return type.
2472 Value *X;
2473 // Sign-bit checks can be optimized to true/false after unsigned
2474 // floating-point casts:
2475 // icmp slt (bitcast (uitofp X)), 0 --> false
2476 // icmp sgt (bitcast (uitofp X)), -1 --> true
2477 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2478 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2479 return ConstantInt::getFalse(ITy);
2480 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2481 return ConstantInt::getTrue(ITy);
2484 const APInt *C;
2485 if (!match(RHS, m_APInt(C)))
2486 return nullptr;
2488 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2489 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2490 if (RHS_CR.isEmptySet())
2491 return ConstantInt::getFalse(ITy);
2492 if (RHS_CR.isFullSet())
2493 return ConstantInt::getTrue(ITy);
2495 ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo);
2496 if (!LHS_CR.isFullSet()) {
2497 if (RHS_CR.contains(LHS_CR))
2498 return ConstantInt::getTrue(ITy);
2499 if (RHS_CR.inverse().contains(LHS_CR))
2500 return ConstantInt::getFalse(ITy);
2503 return nullptr;
2506 /// TODO: A large part of this logic is duplicated in InstCombine's
2507 /// foldICmpBinOp(). We should be able to share that and avoid the code
2508 /// duplication.
2509 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2510 Value *RHS, const SimplifyQuery &Q,
2511 unsigned MaxRecurse) {
2512 Type *ITy = GetCompareTy(LHS); // The return type.
2514 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2515 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2516 if (MaxRecurse && (LBO || RBO)) {
2517 // Analyze the case when either LHS or RHS is an add instruction.
2518 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2519 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2520 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2521 if (LBO && LBO->getOpcode() == Instruction::Add) {
2522 A = LBO->getOperand(0);
2523 B = LBO->getOperand(1);
2524 NoLHSWrapProblem =
2525 ICmpInst::isEquality(Pred) ||
2526 (CmpInst::isUnsigned(Pred) &&
2527 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2528 (CmpInst::isSigned(Pred) &&
2529 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2531 if (RBO && RBO->getOpcode() == Instruction::Add) {
2532 C = RBO->getOperand(0);
2533 D = RBO->getOperand(1);
2534 NoRHSWrapProblem =
2535 ICmpInst::isEquality(Pred) ||
2536 (CmpInst::isUnsigned(Pred) &&
2537 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2538 (CmpInst::isSigned(Pred) &&
2539 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2542 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2543 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2544 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2545 Constant::getNullValue(RHS->getType()), Q,
2546 MaxRecurse - 1))
2547 return V;
2549 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2550 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2551 if (Value *V =
2552 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2553 C == LHS ? D : C, Q, MaxRecurse - 1))
2554 return V;
2556 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2557 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2558 NoRHSWrapProblem) {
2559 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2560 Value *Y, *Z;
2561 if (A == C) {
2562 // C + B == C + D -> B == D
2563 Y = B;
2564 Z = D;
2565 } else if (A == D) {
2566 // D + B == C + D -> B == C
2567 Y = B;
2568 Z = C;
2569 } else if (B == C) {
2570 // A + C == C + D -> A == D
2571 Y = A;
2572 Z = D;
2573 } else {
2574 assert(B == D);
2575 // A + D == C + D -> A == C
2576 Y = A;
2577 Z = C;
2579 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2580 return V;
2585 Value *Y = nullptr;
2586 // icmp pred (or X, Y), X
2587 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2588 if (Pred == ICmpInst::ICMP_ULT)
2589 return getFalse(ITy);
2590 if (Pred == ICmpInst::ICMP_UGE)
2591 return getTrue(ITy);
2593 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2594 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2595 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2596 if (RHSKnown.isNonNegative() && YKnown.isNegative())
2597 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2598 if (RHSKnown.isNegative() || YKnown.isNonNegative())
2599 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2602 // icmp pred X, (or X, Y)
2603 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2604 if (Pred == ICmpInst::ICMP_ULE)
2605 return getTrue(ITy);
2606 if (Pred == ICmpInst::ICMP_UGT)
2607 return getFalse(ITy);
2609 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2610 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2611 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2612 if (LHSKnown.isNonNegative() && YKnown.isNegative())
2613 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2614 if (LHSKnown.isNegative() || YKnown.isNonNegative())
2615 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2620 // icmp pred (and X, Y), X
2621 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2622 if (Pred == ICmpInst::ICMP_UGT)
2623 return getFalse(ITy);
2624 if (Pred == ICmpInst::ICMP_ULE)
2625 return getTrue(ITy);
2627 // icmp pred X, (and X, Y)
2628 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2629 if (Pred == ICmpInst::ICMP_UGE)
2630 return getTrue(ITy);
2631 if (Pred == ICmpInst::ICMP_ULT)
2632 return getFalse(ITy);
2635 // 0 - (zext X) pred C
2636 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2637 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2638 if (RHSC->getValue().isStrictlyPositive()) {
2639 if (Pred == ICmpInst::ICMP_SLT)
2640 return ConstantInt::getTrue(RHSC->getContext());
2641 if (Pred == ICmpInst::ICMP_SGE)
2642 return ConstantInt::getFalse(RHSC->getContext());
2643 if (Pred == ICmpInst::ICMP_EQ)
2644 return ConstantInt::getFalse(RHSC->getContext());
2645 if (Pred == ICmpInst::ICMP_NE)
2646 return ConstantInt::getTrue(RHSC->getContext());
2648 if (RHSC->getValue().isNonNegative()) {
2649 if (Pred == ICmpInst::ICMP_SLE)
2650 return ConstantInt::getTrue(RHSC->getContext());
2651 if (Pred == ICmpInst::ICMP_SGT)
2652 return ConstantInt::getFalse(RHSC->getContext());
2657 // icmp pred (urem X, Y), Y
2658 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2659 switch (Pred) {
2660 default:
2661 break;
2662 case ICmpInst::ICMP_SGT:
2663 case ICmpInst::ICMP_SGE: {
2664 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2665 if (!Known.isNonNegative())
2666 break;
2667 LLVM_FALLTHROUGH;
2669 case ICmpInst::ICMP_EQ:
2670 case ICmpInst::ICMP_UGT:
2671 case ICmpInst::ICMP_UGE:
2672 return getFalse(ITy);
2673 case ICmpInst::ICMP_SLT:
2674 case ICmpInst::ICMP_SLE: {
2675 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2676 if (!Known.isNonNegative())
2677 break;
2678 LLVM_FALLTHROUGH;
2680 case ICmpInst::ICMP_NE:
2681 case ICmpInst::ICMP_ULT:
2682 case ICmpInst::ICMP_ULE:
2683 return getTrue(ITy);
2687 // icmp pred X, (urem Y, X)
2688 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2689 switch (Pred) {
2690 default:
2691 break;
2692 case ICmpInst::ICMP_SGT:
2693 case ICmpInst::ICMP_SGE: {
2694 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2695 if (!Known.isNonNegative())
2696 break;
2697 LLVM_FALLTHROUGH;
2699 case ICmpInst::ICMP_NE:
2700 case ICmpInst::ICMP_UGT:
2701 case ICmpInst::ICMP_UGE:
2702 return getTrue(ITy);
2703 case ICmpInst::ICMP_SLT:
2704 case ICmpInst::ICMP_SLE: {
2705 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2706 if (!Known.isNonNegative())
2707 break;
2708 LLVM_FALLTHROUGH;
2710 case ICmpInst::ICMP_EQ:
2711 case ICmpInst::ICMP_ULT:
2712 case ICmpInst::ICMP_ULE:
2713 return getFalse(ITy);
2717 // x >> y <=u x
2718 // x udiv y <=u x.
2719 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2720 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2721 // icmp pred (X op Y), X
2722 if (Pred == ICmpInst::ICMP_UGT)
2723 return getFalse(ITy);
2724 if (Pred == ICmpInst::ICMP_ULE)
2725 return getTrue(ITy);
2728 // x >=u x >> y
2729 // x >=u x udiv y.
2730 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2731 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2732 // icmp pred X, (X op Y)
2733 if (Pred == ICmpInst::ICMP_ULT)
2734 return getFalse(ITy);
2735 if (Pred == ICmpInst::ICMP_UGE)
2736 return getTrue(ITy);
2739 // handle:
2740 // CI2 << X == CI
2741 // CI2 << X != CI
2743 // where CI2 is a power of 2 and CI isn't
2744 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2745 const APInt *CI2Val, *CIVal = &CI->getValue();
2746 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2747 CI2Val->isPowerOf2()) {
2748 if (!CIVal->isPowerOf2()) {
2749 // CI2 << X can equal zero in some circumstances,
2750 // this simplification is unsafe if CI is zero.
2752 // We know it is safe if:
2753 // - The shift is nsw, we can't shift out the one bit.
2754 // - The shift is nuw, we can't shift out the one bit.
2755 // - CI2 is one
2756 // - CI isn't zero
2757 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2758 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2759 CI2Val->isOneValue() || !CI->isZero()) {
2760 if (Pred == ICmpInst::ICMP_EQ)
2761 return ConstantInt::getFalse(RHS->getContext());
2762 if (Pred == ICmpInst::ICMP_NE)
2763 return ConstantInt::getTrue(RHS->getContext());
2766 if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2767 if (Pred == ICmpInst::ICMP_UGT)
2768 return ConstantInt::getFalse(RHS->getContext());
2769 if (Pred == ICmpInst::ICMP_ULE)
2770 return ConstantInt::getTrue(RHS->getContext());
2775 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2776 LBO->getOperand(1) == RBO->getOperand(1)) {
2777 switch (LBO->getOpcode()) {
2778 default:
2779 break;
2780 case Instruction::UDiv:
2781 case Instruction::LShr:
2782 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
2783 !Q.IIQ.isExact(RBO))
2784 break;
2785 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2786 RBO->getOperand(0), Q, MaxRecurse - 1))
2787 return V;
2788 break;
2789 case Instruction::SDiv:
2790 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
2791 !Q.IIQ.isExact(RBO))
2792 break;
2793 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2794 RBO->getOperand(0), Q, MaxRecurse - 1))
2795 return V;
2796 break;
2797 case Instruction::AShr:
2798 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
2799 break;
2800 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2801 RBO->getOperand(0), Q, MaxRecurse - 1))
2802 return V;
2803 break;
2804 case Instruction::Shl: {
2805 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
2806 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
2807 if (!NUW && !NSW)
2808 break;
2809 if (!NSW && ICmpInst::isSigned(Pred))
2810 break;
2811 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2812 RBO->getOperand(0), Q, MaxRecurse - 1))
2813 return V;
2814 break;
2818 return nullptr;
2821 /// Simplify integer comparisons where at least one operand of the compare
2822 /// matches an integer min/max idiom.
2823 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2824 Value *RHS, const SimplifyQuery &Q,
2825 unsigned MaxRecurse) {
2826 Type *ITy = GetCompareTy(LHS); // The return type.
2827 Value *A, *B;
2828 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2829 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2831 // Signed variants on "max(a,b)>=a -> true".
2832 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2833 if (A != RHS)
2834 std::swap(A, B); // smax(A, B) pred A.
2835 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2836 // We analyze this as smax(A, B) pred A.
2837 P = Pred;
2838 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2839 (A == LHS || B == LHS)) {
2840 if (A != LHS)
2841 std::swap(A, B); // A pred smax(A, B).
2842 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2843 // We analyze this as smax(A, B) swapped-pred A.
2844 P = CmpInst::getSwappedPredicate(Pred);
2845 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2846 (A == RHS || B == RHS)) {
2847 if (A != RHS)
2848 std::swap(A, B); // smin(A, B) pred A.
2849 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2850 // We analyze this as smax(-A, -B) swapped-pred -A.
2851 // Note that we do not need to actually form -A or -B thanks to EqP.
2852 P = CmpInst::getSwappedPredicate(Pred);
2853 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2854 (A == LHS || B == LHS)) {
2855 if (A != LHS)
2856 std::swap(A, B); // A pred smin(A, B).
2857 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2858 // We analyze this as smax(-A, -B) pred -A.
2859 // Note that we do not need to actually form -A or -B thanks to EqP.
2860 P = Pred;
2862 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2863 // Cases correspond to "max(A, B) p A".
2864 switch (P) {
2865 default:
2866 break;
2867 case CmpInst::ICMP_EQ:
2868 case CmpInst::ICMP_SLE:
2869 // Equivalent to "A EqP B". This may be the same as the condition tested
2870 // in the max/min; if so, we can just return that.
2871 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2872 return V;
2873 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2874 return V;
2875 // Otherwise, see if "A EqP B" simplifies.
2876 if (MaxRecurse)
2877 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2878 return V;
2879 break;
2880 case CmpInst::ICMP_NE:
2881 case CmpInst::ICMP_SGT: {
2882 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2883 // Equivalent to "A InvEqP B". This may be the same as the condition
2884 // tested in the max/min; if so, we can just return that.
2885 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2886 return V;
2887 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2888 return V;
2889 // Otherwise, see if "A InvEqP B" simplifies.
2890 if (MaxRecurse)
2891 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2892 return V;
2893 break;
2895 case CmpInst::ICMP_SGE:
2896 // Always true.
2897 return getTrue(ITy);
2898 case CmpInst::ICMP_SLT:
2899 // Always false.
2900 return getFalse(ITy);
2904 // Unsigned variants on "max(a,b)>=a -> true".
2905 P = CmpInst::BAD_ICMP_PREDICATE;
2906 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2907 if (A != RHS)
2908 std::swap(A, B); // umax(A, B) pred A.
2909 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2910 // We analyze this as umax(A, B) pred A.
2911 P = Pred;
2912 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2913 (A == LHS || B == LHS)) {
2914 if (A != LHS)
2915 std::swap(A, B); // A pred umax(A, B).
2916 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2917 // We analyze this as umax(A, B) swapped-pred A.
2918 P = CmpInst::getSwappedPredicate(Pred);
2919 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2920 (A == RHS || B == RHS)) {
2921 if (A != RHS)
2922 std::swap(A, B); // umin(A, B) pred A.
2923 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2924 // We analyze this as umax(-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_UMin(m_Value(A), m_Value(B))) &&
2928 (A == LHS || B == LHS)) {
2929 if (A != LHS)
2930 std::swap(A, B); // A pred umin(A, B).
2931 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2932 // We analyze this as umax(-A, -B) pred -A.
2933 // Note that we do not need to actually form -A or -B thanks to EqP.
2934 P = Pred;
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_ULE:
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_UGT: {
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;
2969 case CmpInst::ICMP_UGE:
2970 // Always true.
2971 return getTrue(ITy);
2972 case CmpInst::ICMP_ULT:
2973 // Always false.
2974 return getFalse(ITy);
2978 // Variants on "max(x,y) >= min(x,z)".
2979 Value *C, *D;
2980 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2981 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2982 (A == C || A == D || B == C || B == D)) {
2983 // max(x, ?) pred min(x, ?).
2984 if (Pred == CmpInst::ICMP_SGE)
2985 // Always true.
2986 return getTrue(ITy);
2987 if (Pred == CmpInst::ICMP_SLT)
2988 // Always false.
2989 return getFalse(ITy);
2990 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2991 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2992 (A == C || A == D || B == C || B == D)) {
2993 // min(x, ?) pred max(x, ?).
2994 if (Pred == CmpInst::ICMP_SLE)
2995 // Always true.
2996 return getTrue(ITy);
2997 if (Pred == CmpInst::ICMP_SGT)
2998 // Always false.
2999 return getFalse(ITy);
3000 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3001 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3002 (A == C || A == D || B == C || B == D)) {
3003 // max(x, ?) pred min(x, ?).
3004 if (Pred == CmpInst::ICMP_UGE)
3005 // Always true.
3006 return getTrue(ITy);
3007 if (Pred == CmpInst::ICMP_ULT)
3008 // Always false.
3009 return getFalse(ITy);
3010 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3011 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3012 (A == C || A == D || B == C || B == D)) {
3013 // min(x, ?) pred max(x, ?).
3014 if (Pred == CmpInst::ICMP_ULE)
3015 // Always true.
3016 return getTrue(ITy);
3017 if (Pred == CmpInst::ICMP_UGT)
3018 // Always false.
3019 return getFalse(ITy);
3022 return nullptr;
3025 /// Given operands for an ICmpInst, see if we can fold the result.
3026 /// If not, this returns null.
3027 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3028 const SimplifyQuery &Q, unsigned MaxRecurse) {
3029 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3030 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3032 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3033 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3034 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3036 // If we have a constant, make sure it is on the RHS.
3037 std::swap(LHS, RHS);
3038 Pred = CmpInst::getSwappedPredicate(Pred);
3040 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3042 Type *ITy = GetCompareTy(LHS); // The return type.
3044 // For EQ and NE, we can always pick a value for the undef to make the
3045 // predicate pass or fail, so we can return undef.
3046 // Matches behavior in llvm::ConstantFoldCompareInstruction.
3047 if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3048 return UndefValue::get(ITy);
3050 // icmp X, X -> true/false
3051 // icmp X, undef -> true/false because undef could be X.
3052 if (LHS == RHS || isa<UndefValue>(RHS))
3053 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3055 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3056 return V;
3058 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3059 return V;
3061 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3062 return V;
3064 // If both operands have range metadata, use the metadata
3065 // to simplify the comparison.
3066 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3067 auto RHS_Instr = cast<Instruction>(RHS);
3068 auto LHS_Instr = cast<Instruction>(LHS);
3070 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3071 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3072 auto RHS_CR = getConstantRangeFromMetadata(
3073 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3074 auto LHS_CR = getConstantRangeFromMetadata(
3075 *LHS_Instr->getMetadata(LLVMContext::MD_range));
3077 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3078 if (Satisfied_CR.contains(LHS_CR))
3079 return ConstantInt::getTrue(RHS->getContext());
3081 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3082 CmpInst::getInversePredicate(Pred), RHS_CR);
3083 if (InversedSatisfied_CR.contains(LHS_CR))
3084 return ConstantInt::getFalse(RHS->getContext());
3088 // Compare of cast, for example (zext X) != 0 -> X != 0
3089 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3090 Instruction *LI = cast<CastInst>(LHS);
3091 Value *SrcOp = LI->getOperand(0);
3092 Type *SrcTy = SrcOp->getType();
3093 Type *DstTy = LI->getType();
3095 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3096 // if the integer type is the same size as the pointer type.
3097 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3098 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3099 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3100 // Transfer the cast to the constant.
3101 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3102 ConstantExpr::getIntToPtr(RHSC, SrcTy),
3103 Q, MaxRecurse-1))
3104 return V;
3105 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3106 if (RI->getOperand(0)->getType() == SrcTy)
3107 // Compare without the cast.
3108 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3109 Q, MaxRecurse-1))
3110 return V;
3114 if (isa<ZExtInst>(LHS)) {
3115 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3116 // same type.
3117 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3118 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3119 // Compare X and Y. Note that signed predicates become unsigned.
3120 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3121 SrcOp, RI->getOperand(0), Q,
3122 MaxRecurse-1))
3123 return V;
3125 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3126 // too. If not, then try to deduce the result of the comparison.
3127 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3128 // Compute the constant that would happen if we truncated to SrcTy then
3129 // reextended to DstTy.
3130 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3131 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3133 // If the re-extended constant didn't change then this is effectively
3134 // also a case of comparing two zero-extended values.
3135 if (RExt == CI && MaxRecurse)
3136 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3137 SrcOp, Trunc, Q, MaxRecurse-1))
3138 return V;
3140 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3141 // there. Use this to work out the result of the comparison.
3142 if (RExt != CI) {
3143 switch (Pred) {
3144 default: llvm_unreachable("Unknown ICmp predicate!");
3145 // LHS <u RHS.
3146 case ICmpInst::ICMP_EQ:
3147 case ICmpInst::ICMP_UGT:
3148 case ICmpInst::ICMP_UGE:
3149 return ConstantInt::getFalse(CI->getContext());
3151 case ICmpInst::ICMP_NE:
3152 case ICmpInst::ICMP_ULT:
3153 case ICmpInst::ICMP_ULE:
3154 return ConstantInt::getTrue(CI->getContext());
3156 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3157 // is non-negative then LHS <s RHS.
3158 case ICmpInst::ICMP_SGT:
3159 case ICmpInst::ICMP_SGE:
3160 return CI->getValue().isNegative() ?
3161 ConstantInt::getTrue(CI->getContext()) :
3162 ConstantInt::getFalse(CI->getContext());
3164 case ICmpInst::ICMP_SLT:
3165 case ICmpInst::ICMP_SLE:
3166 return CI->getValue().isNegative() ?
3167 ConstantInt::getFalse(CI->getContext()) :
3168 ConstantInt::getTrue(CI->getContext());
3174 if (isa<SExtInst>(LHS)) {
3175 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3176 // same type.
3177 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3178 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3179 // Compare X and Y. Note that the predicate does not change.
3180 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3181 Q, MaxRecurse-1))
3182 return V;
3184 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3185 // too. If not, then try to deduce the result of the comparison.
3186 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3187 // Compute the constant that would happen if we truncated to SrcTy then
3188 // reextended to DstTy.
3189 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3190 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3192 // If the re-extended constant didn't change then this is effectively
3193 // also a case of comparing two sign-extended values.
3194 if (RExt == CI && MaxRecurse)
3195 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3196 return V;
3198 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3199 // bits there. Use this to work out the result of the comparison.
3200 if (RExt != CI) {
3201 switch (Pred) {
3202 default: llvm_unreachable("Unknown ICmp predicate!");
3203 case ICmpInst::ICMP_EQ:
3204 return ConstantInt::getFalse(CI->getContext());
3205 case ICmpInst::ICMP_NE:
3206 return ConstantInt::getTrue(CI->getContext());
3208 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3209 // LHS >s RHS.
3210 case ICmpInst::ICMP_SGT:
3211 case ICmpInst::ICMP_SGE:
3212 return CI->getValue().isNegative() ?
3213 ConstantInt::getTrue(CI->getContext()) :
3214 ConstantInt::getFalse(CI->getContext());
3215 case ICmpInst::ICMP_SLT:
3216 case ICmpInst::ICMP_SLE:
3217 return CI->getValue().isNegative() ?
3218 ConstantInt::getFalse(CI->getContext()) :
3219 ConstantInt::getTrue(CI->getContext());
3221 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3222 // LHS >u RHS.
3223 case ICmpInst::ICMP_UGT:
3224 case ICmpInst::ICMP_UGE:
3225 // Comparison is true iff the LHS <s 0.
3226 if (MaxRecurse)
3227 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3228 Constant::getNullValue(SrcTy),
3229 Q, MaxRecurse-1))
3230 return V;
3231 break;
3232 case ICmpInst::ICMP_ULT:
3233 case ICmpInst::ICMP_ULE:
3234 // Comparison is true iff the LHS >=s 0.
3235 if (MaxRecurse)
3236 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3237 Constant::getNullValue(SrcTy),
3238 Q, MaxRecurse-1))
3239 return V;
3240 break;
3247 // icmp eq|ne X, Y -> false|true if X != Y
3248 if (ICmpInst::isEquality(Pred) &&
3249 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3250 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3253 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3254 return V;
3256 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3257 return V;
3259 // Simplify comparisons of related pointers using a powerful, recursive
3260 // GEP-walk when we have target data available..
3261 if (LHS->getType()->isPointerTy())
3262 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3263 Q.IIQ, LHS, RHS))
3264 return C;
3265 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3266 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3267 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3268 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3269 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3270 Q.DL.getTypeSizeInBits(CRHS->getType()))
3271 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3272 Q.IIQ, CLHS->getPointerOperand(),
3273 CRHS->getPointerOperand()))
3274 return C;
3276 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3277 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3278 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3279 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3280 (ICmpInst::isEquality(Pred) ||
3281 (GLHS->isInBounds() && GRHS->isInBounds() &&
3282 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3283 // The bases are equal and the indices are constant. Build a constant
3284 // expression GEP with the same indices and a null base pointer to see
3285 // what constant folding can make out of it.
3286 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3287 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3288 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3289 GLHS->getSourceElementType(), Null, IndicesLHS);
3291 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3292 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3293 GLHS->getSourceElementType(), Null, IndicesRHS);
3294 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3299 // If the comparison is with the result of a select instruction, check whether
3300 // comparing with either branch of the select always yields the same value.
3301 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3302 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3303 return V;
3305 // If the comparison is with the result of a phi instruction, check whether
3306 // doing the compare with each incoming phi value yields a common result.
3307 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3308 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3309 return V;
3311 return nullptr;
3314 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3315 const SimplifyQuery &Q) {
3316 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3319 /// Given operands for an FCmpInst, see if we can fold the result.
3320 /// If not, this returns null.
3321 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3322 FastMathFlags FMF, const SimplifyQuery &Q,
3323 unsigned MaxRecurse) {
3324 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3325 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3327 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3328 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3329 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3331 // If we have a constant, make sure it is on the RHS.
3332 std::swap(LHS, RHS);
3333 Pred = CmpInst::getSwappedPredicate(Pred);
3336 // Fold trivial predicates.
3337 Type *RetTy = GetCompareTy(LHS);
3338 if (Pred == FCmpInst::FCMP_FALSE)
3339 return getFalse(RetTy);
3340 if (Pred == FCmpInst::FCMP_TRUE)
3341 return getTrue(RetTy);
3343 // Fold (un)ordered comparison if we can determine there are no NaNs.
3344 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3345 if (FMF.noNaNs() ||
3346 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3347 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3349 // NaN is unordered; NaN is not ordered.
3350 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3351 "Comparison must be either ordered or unordered");
3352 if (match(RHS, m_NaN()))
3353 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3355 // fcmp pred x, undef and fcmp pred undef, x
3356 // fold to true if unordered, false if ordered
3357 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3358 // Choosing NaN for the undef will always make unordered comparison succeed
3359 // and ordered comparison fail.
3360 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3363 // fcmp x,x -> true/false. Not all compares are foldable.
3364 if (LHS == RHS) {
3365 if (CmpInst::isTrueWhenEqual(Pred))
3366 return getTrue(RetTy);
3367 if (CmpInst::isFalseWhenEqual(Pred))
3368 return getFalse(RetTy);
3371 // Handle fcmp with constant RHS.
3372 // TODO: Use match with a specific FP value, so these work with vectors with
3373 // undef lanes.
3374 const APFloat *C;
3375 if (match(RHS, m_APFloat(C))) {
3376 // Check whether the constant is an infinity.
3377 if (C->isInfinity()) {
3378 if (C->isNegative()) {
3379 switch (Pred) {
3380 case FCmpInst::FCMP_OLT:
3381 // No value is ordered and less than negative infinity.
3382 return getFalse(RetTy);
3383 case FCmpInst::FCMP_UGE:
3384 // All values are unordered with or at least negative infinity.
3385 return getTrue(RetTy);
3386 default:
3387 break;
3389 } else {
3390 switch (Pred) {
3391 case FCmpInst::FCMP_OGT:
3392 // No value is ordered and greater than infinity.
3393 return getFalse(RetTy);
3394 case FCmpInst::FCMP_ULE:
3395 // All values are unordered with and at most infinity.
3396 return getTrue(RetTy);
3397 default:
3398 break;
3402 if (C->isNegative() && !C->isNegZero()) {
3403 assert(!C->isNaN() && "Unexpected NaN constant!");
3404 // TODO: We can catch more cases by using a range check rather than
3405 // relying on CannotBeOrderedLessThanZero.
3406 switch (Pred) {
3407 case FCmpInst::FCMP_UGE:
3408 case FCmpInst::FCMP_UGT:
3409 case FCmpInst::FCMP_UNE:
3410 // (X >= 0) implies (X > C) when (C < 0)
3411 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3412 return getTrue(RetTy);
3413 break;
3414 case FCmpInst::FCMP_OEQ:
3415 case FCmpInst::FCMP_OLE:
3416 case FCmpInst::FCMP_OLT:
3417 // (X >= 0) implies !(X < C) when (C < 0)
3418 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3419 return getFalse(RetTy);
3420 break;
3421 default:
3422 break;
3426 // Check comparison of [minnum/maxnum with constant] with other constant.
3427 const APFloat *C2;
3428 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3429 C2->compare(*C) == APFloat::cmpLessThan) ||
3430 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3431 C2->compare(*C) == APFloat::cmpGreaterThan)) {
3432 bool IsMaxNum =
3433 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3434 // The ordered relationship and minnum/maxnum guarantee that we do not
3435 // have NaN constants, so ordered/unordered preds are handled the same.
3436 switch (Pred) {
3437 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3438 // minnum(X, LesserC) == C --> false
3439 // maxnum(X, GreaterC) == C --> false
3440 return getFalse(RetTy);
3441 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3442 // minnum(X, LesserC) != C --> true
3443 // maxnum(X, GreaterC) != C --> true
3444 return getTrue(RetTy);
3445 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3446 case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3447 // minnum(X, LesserC) >= C --> false
3448 // minnum(X, LesserC) > C --> false
3449 // maxnum(X, GreaterC) >= C --> true
3450 // maxnum(X, GreaterC) > C --> true
3451 return ConstantInt::get(RetTy, IsMaxNum);
3452 case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3453 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3454 // minnum(X, LesserC) <= C --> true
3455 // minnum(X, LesserC) < C --> true
3456 // maxnum(X, GreaterC) <= C --> false
3457 // maxnum(X, GreaterC) < C --> false
3458 return ConstantInt::get(RetTy, !IsMaxNum);
3459 default:
3460 // TRUE/FALSE/ORD/UNO should be handled before this.
3461 llvm_unreachable("Unexpected fcmp predicate");
3466 if (match(RHS, m_AnyZeroFP())) {
3467 switch (Pred) {
3468 case FCmpInst::FCMP_OGE:
3469 case FCmpInst::FCMP_ULT:
3470 // Positive or zero X >= 0.0 --> true
3471 // Positive or zero X < 0.0 --> false
3472 if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3473 CannotBeOrderedLessThanZero(LHS, Q.TLI))
3474 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3475 break;
3476 case FCmpInst::FCMP_UGE:
3477 case FCmpInst::FCMP_OLT:
3478 // Positive or zero or nan X >= 0.0 --> true
3479 // Positive or zero or nan X < 0.0 --> false
3480 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3481 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3482 break;
3483 default:
3484 break;
3488 // If the comparison is with the result of a select instruction, check whether
3489 // comparing with either branch of the select always yields the same value.
3490 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3491 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3492 return V;
3494 // If the comparison is with the result of a phi instruction, check whether
3495 // doing the compare with each incoming phi value yields a common result.
3496 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3497 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3498 return V;
3500 return nullptr;
3503 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3504 FastMathFlags FMF, const SimplifyQuery &Q) {
3505 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3508 /// See if V simplifies when its operand Op is replaced with RepOp.
3509 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3510 const SimplifyQuery &Q,
3511 unsigned MaxRecurse) {
3512 // Trivial replacement.
3513 if (V == Op)
3514 return RepOp;
3516 // We cannot replace a constant, and shouldn't even try.
3517 if (isa<Constant>(Op))
3518 return nullptr;
3520 auto *I = dyn_cast<Instruction>(V);
3521 if (!I)
3522 return nullptr;
3524 // If this is a binary operator, try to simplify it with the replaced op.
3525 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3526 // Consider:
3527 // %cmp = icmp eq i32 %x, 2147483647
3528 // %add = add nsw i32 %x, 1
3529 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3531 // We can't replace %sel with %add unless we strip away the flags.
3532 // TODO: This is an unusual limitation because better analysis results in
3533 // worse simplification. InstCombine can do this fold more generally
3534 // by dropping the flags. Remove this fold to save compile-time?
3535 if (isa<OverflowingBinaryOperator>(B))
3536 if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3537 return nullptr;
3538 if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3539 return nullptr;
3541 if (MaxRecurse) {
3542 if (B->getOperand(0) == Op)
3543 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3544 MaxRecurse - 1);
3545 if (B->getOperand(1) == Op)
3546 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3547 MaxRecurse - 1);
3551 // Same for CmpInsts.
3552 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3553 if (MaxRecurse) {
3554 if (C->getOperand(0) == Op)
3555 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3556 MaxRecurse - 1);
3557 if (C->getOperand(1) == Op)
3558 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3559 MaxRecurse - 1);
3563 // Same for GEPs.
3564 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3565 if (MaxRecurse) {
3566 SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3567 transform(GEP->operands(), NewOps.begin(),
3568 [&](Value *V) { return V == Op ? RepOp : V; });
3569 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3570 MaxRecurse - 1);
3574 // TODO: We could hand off more cases to instsimplify here.
3576 // If all operands are constant after substituting Op for RepOp then we can
3577 // constant fold the instruction.
3578 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3579 // Build a list of all constant operands.
3580 SmallVector<Constant *, 8> ConstOps;
3581 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3582 if (I->getOperand(i) == Op)
3583 ConstOps.push_back(CRepOp);
3584 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3585 ConstOps.push_back(COp);
3586 else
3587 break;
3590 // All operands were constants, fold it.
3591 if (ConstOps.size() == I->getNumOperands()) {
3592 if (CmpInst *C = dyn_cast<CmpInst>(I))
3593 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3594 ConstOps[1], Q.DL, Q.TLI);
3596 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3597 if (!LI->isVolatile())
3598 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3600 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3604 return nullptr;
3607 /// Try to simplify a select instruction when its condition operand is an
3608 /// integer comparison where one operand of the compare is a constant.
3609 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3610 const APInt *Y, bool TrueWhenUnset) {
3611 const APInt *C;
3613 // (X & Y) == 0 ? X & ~Y : X --> X
3614 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3615 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3616 *Y == ~*C)
3617 return TrueWhenUnset ? FalseVal : TrueVal;
3619 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3620 // (X & Y) != 0 ? X : X & ~Y --> X
3621 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3622 *Y == ~*C)
3623 return TrueWhenUnset ? FalseVal : TrueVal;
3625 if (Y->isPowerOf2()) {
3626 // (X & Y) == 0 ? X | Y : X --> X | Y
3627 // (X & Y) != 0 ? X | Y : X --> X
3628 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3629 *Y == *C)
3630 return TrueWhenUnset ? TrueVal : FalseVal;
3632 // (X & Y) == 0 ? X : X | Y --> X
3633 // (X & Y) != 0 ? X : X | Y --> X | Y
3634 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3635 *Y == *C)
3636 return TrueWhenUnset ? TrueVal : FalseVal;
3639 return nullptr;
3642 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3643 /// eq/ne.
3644 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3645 ICmpInst::Predicate Pred,
3646 Value *TrueVal, Value *FalseVal) {
3647 Value *X;
3648 APInt Mask;
3649 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3650 return nullptr;
3652 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3653 Pred == ICmpInst::ICMP_EQ);
3656 /// Try to simplify a select instruction when its condition operand is an
3657 /// integer comparison.
3658 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3659 Value *FalseVal, const SimplifyQuery &Q,
3660 unsigned MaxRecurse) {
3661 ICmpInst::Predicate Pred;
3662 Value *CmpLHS, *CmpRHS;
3663 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3664 return nullptr;
3666 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3667 Value *X;
3668 const APInt *Y;
3669 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3670 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3671 Pred == ICmpInst::ICMP_EQ))
3672 return V;
3674 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
3675 Value *ShAmt;
3676 auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3677 m_Value(ShAmt)),
3678 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3679 m_Value(ShAmt)));
3680 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3681 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3682 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3683 Pred == ICmpInst::ICMP_EQ)
3684 return X;
3685 // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3686 // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3687 if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3688 Pred == ICmpInst::ICMP_NE)
3689 return X;
3691 // Test for a zero-shift-guard-op around rotates. These are used to
3692 // avoid UB from oversized shifts in raw IR rotate patterns, but the
3693 // intrinsics do not have that problem.
3694 // We do not allow this transform for the general funnel shift case because
3695 // that would not preserve the poison safety of the original code.
3696 auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3697 m_Deferred(X),
3698 m_Value(ShAmt)),
3699 m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3700 m_Deferred(X),
3701 m_Value(ShAmt)));
3702 // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3703 // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3704 if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3705 Pred == ICmpInst::ICMP_NE)
3706 return TrueVal;
3707 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3708 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3709 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3710 Pred == ICmpInst::ICMP_EQ)
3711 return FalseVal;
3714 // Check for other compares that behave like bit test.
3715 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3716 TrueVal, FalseVal))
3717 return V;
3719 // If we have an equality comparison, then we know the value in one of the
3720 // arms of the select. See if substituting this value into the arm and
3721 // simplifying the result yields the same value as the other arm.
3722 if (Pred == ICmpInst::ICMP_EQ) {
3723 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3724 TrueVal ||
3725 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3726 TrueVal)
3727 return FalseVal;
3728 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3729 FalseVal ||
3730 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3731 FalseVal)
3732 return FalseVal;
3733 } else if (Pred == ICmpInst::ICMP_NE) {
3734 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3735 FalseVal ||
3736 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3737 FalseVal)
3738 return TrueVal;
3739 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3740 TrueVal ||
3741 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3742 TrueVal)
3743 return TrueVal;
3746 return nullptr;
3749 /// Try to simplify a select instruction when its condition operand is a
3750 /// floating-point comparison.
3751 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3752 FCmpInst::Predicate Pred;
3753 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3754 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3755 return nullptr;
3757 // TODO: The transform may not be valid with -0.0. An incomplete way of
3758 // testing for that possibility is to check if at least one operand is a
3759 // non-zero constant.
3760 const APFloat *C;
3761 if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3762 (match(F, m_APFloat(C)) && C->isNonZero())) {
3763 // (T == F) ? T : F --> F
3764 // (F == T) ? T : F --> F
3765 if (Pred == FCmpInst::FCMP_OEQ)
3766 return F;
3768 // (T != F) ? T : F --> T
3769 // (F != T) ? T : F --> T
3770 if (Pred == FCmpInst::FCMP_UNE)
3771 return T;
3774 return nullptr;
3777 /// Given operands for a SelectInst, see if we can fold the result.
3778 /// If not, this returns null.
3779 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3780 const SimplifyQuery &Q, unsigned MaxRecurse) {
3781 if (auto *CondC = dyn_cast<Constant>(Cond)) {
3782 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3783 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3784 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3786 // select undef, X, Y -> X or Y
3787 if (isa<UndefValue>(CondC))
3788 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3790 // TODO: Vector constants with undef elements don't simplify.
3792 // select true, X, Y -> X
3793 if (CondC->isAllOnesValue())
3794 return TrueVal;
3795 // select false, X, Y -> Y
3796 if (CondC->isNullValue())
3797 return FalseVal;
3800 // select ?, X, X -> X
3801 if (TrueVal == FalseVal)
3802 return TrueVal;
3804 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
3805 return FalseVal;
3806 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
3807 return TrueVal;
3809 if (Value *V =
3810 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
3811 return V;
3813 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
3814 return V;
3816 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
3817 return V;
3819 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
3820 if (Imp)
3821 return *Imp ? TrueVal : FalseVal;
3823 return nullptr;
3826 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3827 const SimplifyQuery &Q) {
3828 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
3831 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3832 /// If not, this returns null.
3833 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3834 const SimplifyQuery &Q, unsigned) {
3835 // The type of the GEP pointer operand.
3836 unsigned AS =
3837 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3839 // getelementptr P -> P.
3840 if (Ops.size() == 1)
3841 return Ops[0];
3843 // Compute the (pointer) type returned by the GEP instruction.
3844 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3845 Type *GEPTy = PointerType::get(LastType, AS);
3846 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3847 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3848 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3849 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3851 if (isa<UndefValue>(Ops[0]))
3852 return UndefValue::get(GEPTy);
3854 if (Ops.size() == 2) {
3855 // getelementptr P, 0 -> P.
3856 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
3857 return Ops[0];
3859 Type *Ty = SrcTy;
3860 if (Ty->isSized()) {
3861 Value *P;
3862 uint64_t C;
3863 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3864 // getelementptr P, N -> P if P points to a type of zero size.
3865 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
3866 return Ops[0];
3868 // The following transforms are only safe if the ptrtoint cast
3869 // doesn't truncate the pointers.
3870 if (Ops[1]->getType()->getScalarSizeInBits() ==
3871 Q.DL.getIndexSizeInBits(AS)) {
3872 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3873 if (match(P, m_Zero()))
3874 return Constant::getNullValue(GEPTy);
3875 Value *Temp;
3876 if (match(P, m_PtrToInt(m_Value(Temp))))
3877 if (Temp->getType() == GEPTy)
3878 return Temp;
3879 return nullptr;
3882 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3883 if (TyAllocSize == 1 &&
3884 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3885 if (Value *R = PtrToIntOrZero(P))
3886 return R;
3888 // getelementptr V, (ashr (sub P, V), C) -> Q
3889 // if P points to a type of size 1 << C.
3890 if (match(Ops[1],
3891 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3892 m_ConstantInt(C))) &&
3893 TyAllocSize == 1ULL << C)
3894 if (Value *R = PtrToIntOrZero(P))
3895 return R;
3897 // getelementptr V, (sdiv (sub P, V), C) -> Q
3898 // if P points to a type of size C.
3899 if (match(Ops[1],
3900 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3901 m_SpecificInt(TyAllocSize))))
3902 if (Value *R = PtrToIntOrZero(P))
3903 return R;
3908 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3909 all_of(Ops.slice(1).drop_back(1),
3910 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3911 unsigned IdxWidth =
3912 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3913 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
3914 APInt BasePtrOffset(IdxWidth, 0);
3915 Value *StrippedBasePtr =
3916 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3917 BasePtrOffset);
3919 // gep (gep V, C), (sub 0, V) -> C
3920 if (match(Ops.back(),
3921 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3922 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3923 return ConstantExpr::getIntToPtr(CI, GEPTy);
3925 // gep (gep V, C), (xor V, -1) -> C-1
3926 if (match(Ops.back(),
3927 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3928 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3929 return ConstantExpr::getIntToPtr(CI, GEPTy);
3934 // Check to see if this is constant foldable.
3935 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
3936 return nullptr;
3938 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3939 Ops.slice(1));
3940 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
3941 return CEFolded;
3942 return CE;
3945 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3946 const SimplifyQuery &Q) {
3947 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
3950 /// Given operands for an InsertValueInst, see if we can fold the result.
3951 /// If not, this returns null.
3952 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3953 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
3954 unsigned) {
3955 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3956 if (Constant *CVal = dyn_cast<Constant>(Val))
3957 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3959 // insertvalue x, undef, n -> x
3960 if (match(Val, m_Undef()))
3961 return Agg;
3963 // insertvalue x, (extractvalue y, n), n
3964 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3965 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3966 EV->getIndices() == Idxs) {
3967 // insertvalue undef, (extractvalue y, n), n -> y
3968 if (match(Agg, m_Undef()))
3969 return EV->getAggregateOperand();
3971 // insertvalue y, (extractvalue y, n), n -> y
3972 if (Agg == EV->getAggregateOperand())
3973 return Agg;
3976 return nullptr;
3979 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3980 ArrayRef<unsigned> Idxs,
3981 const SimplifyQuery &Q) {
3982 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3985 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
3986 const SimplifyQuery &Q) {
3987 // Try to constant fold.
3988 auto *VecC = dyn_cast<Constant>(Vec);
3989 auto *ValC = dyn_cast<Constant>(Val);
3990 auto *IdxC = dyn_cast<Constant>(Idx);
3991 if (VecC && ValC && IdxC)
3992 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
3994 // Fold into undef if index is out of bounds.
3995 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
3996 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
3997 if (CI->uge(NumElements))
3998 return UndefValue::get(Vec->getType());
4001 // If index is undef, it might be out of bounds (see above case)
4002 if (isa<UndefValue>(Idx))
4003 return UndefValue::get(Vec->getType());
4005 // Inserting an undef scalar? Assume it is the same value as the existing
4006 // vector element.
4007 if (isa<UndefValue>(Val))
4008 return Vec;
4010 // If we are extracting a value from a vector, then inserting it into the same
4011 // place, that's the input vector:
4012 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4013 if (match(Val, m_ExtractElement(m_Specific(Vec), m_Specific(Idx))))
4014 return Vec;
4016 return nullptr;
4019 /// Given operands for an ExtractValueInst, see if we can fold the result.
4020 /// If not, this returns null.
4021 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4022 const SimplifyQuery &, unsigned) {
4023 if (auto *CAgg = dyn_cast<Constant>(Agg))
4024 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4026 // extractvalue x, (insertvalue y, elt, n), n -> elt
4027 unsigned NumIdxs = Idxs.size();
4028 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4029 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4030 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4031 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4032 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4033 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4034 Idxs.slice(0, NumCommonIdxs)) {
4035 if (NumIdxs == NumInsertValueIdxs)
4036 return IVI->getInsertedValueOperand();
4037 break;
4041 return nullptr;
4044 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4045 const SimplifyQuery &Q) {
4046 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4049 /// Given operands for an ExtractElementInst, see if we can fold the result.
4050 /// If not, this returns null.
4051 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
4052 unsigned) {
4053 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4054 if (auto *CIdx = dyn_cast<Constant>(Idx))
4055 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4057 // The index is not relevant if our vector is a splat.
4058 if (auto *Splat = CVec->getSplatValue())
4059 return Splat;
4061 if (isa<UndefValue>(Vec))
4062 return UndefValue::get(Vec->getType()->getVectorElementType());
4065 // If extracting a specified index from the vector, see if we can recursively
4066 // find a previously computed scalar that was inserted into the vector.
4067 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4068 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4069 // definitely out of bounds, thus undefined result
4070 return UndefValue::get(Vec->getType()->getVectorElementType());
4071 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4072 return Elt;
4075 // An undef extract index can be arbitrarily chosen to be an out-of-range
4076 // index value, which would result in the instruction being undef.
4077 if (isa<UndefValue>(Idx))
4078 return UndefValue::get(Vec->getType()->getVectorElementType());
4080 return nullptr;
4083 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4084 const SimplifyQuery &Q) {
4085 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4088 /// See if we can fold the given phi. If not, returns null.
4089 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4090 // If all of the PHI's incoming values are the same then replace the PHI node
4091 // with the common value.
4092 Value *CommonValue = nullptr;
4093 bool HasUndefInput = false;
4094 for (Value *Incoming : PN->incoming_values()) {
4095 // If the incoming value is the phi node itself, it can safely be skipped.
4096 if (Incoming == PN) continue;
4097 if (isa<UndefValue>(Incoming)) {
4098 // Remember that we saw an undef value, but otherwise ignore them.
4099 HasUndefInput = true;
4100 continue;
4102 if (CommonValue && Incoming != CommonValue)
4103 return nullptr; // Not the same, bail out.
4104 CommonValue = Incoming;
4107 // If CommonValue is null then all of the incoming values were either undef or
4108 // equal to the phi node itself.
4109 if (!CommonValue)
4110 return UndefValue::get(PN->getType());
4112 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4113 // instruction, we cannot return X as the result of the PHI node unless it
4114 // dominates the PHI block.
4115 if (HasUndefInput)
4116 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4118 return CommonValue;
4121 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4122 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4123 if (auto *C = dyn_cast<Constant>(Op))
4124 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4126 if (auto *CI = dyn_cast<CastInst>(Op)) {
4127 auto *Src = CI->getOperand(0);
4128 Type *SrcTy = Src->getType();
4129 Type *MidTy = CI->getType();
4130 Type *DstTy = Ty;
4131 if (Src->getType() == Ty) {
4132 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4133 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4134 Type *SrcIntPtrTy =
4135 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4136 Type *MidIntPtrTy =
4137 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4138 Type *DstIntPtrTy =
4139 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4140 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4141 SrcIntPtrTy, MidIntPtrTy,
4142 DstIntPtrTy) == Instruction::BitCast)
4143 return Src;
4147 // bitcast x -> x
4148 if (CastOpc == Instruction::BitCast)
4149 if (Op->getType() == Ty)
4150 return Op;
4152 return nullptr;
4155 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4156 const SimplifyQuery &Q) {
4157 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4160 /// For the given destination element of a shuffle, peek through shuffles to
4161 /// match a root vector source operand that contains that element in the same
4162 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4163 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4164 int MaskVal, Value *RootVec,
4165 unsigned MaxRecurse) {
4166 if (!MaxRecurse--)
4167 return nullptr;
4169 // Bail out if any mask value is undefined. That kind of shuffle may be
4170 // simplified further based on demanded bits or other folds.
4171 if (MaskVal == -1)
4172 return nullptr;
4174 // The mask value chooses which source operand we need to look at next.
4175 int InVecNumElts = Op0->getType()->getVectorNumElements();
4176 int RootElt = MaskVal;
4177 Value *SourceOp = Op0;
4178 if (MaskVal >= InVecNumElts) {
4179 RootElt = MaskVal - InVecNumElts;
4180 SourceOp = Op1;
4183 // If the source operand is a shuffle itself, look through it to find the
4184 // matching root vector.
4185 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4186 return foldIdentityShuffles(
4187 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4188 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4191 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4192 // size?
4194 // The source operand is not a shuffle. Initialize the root vector value for
4195 // this shuffle if that has not been done yet.
4196 if (!RootVec)
4197 RootVec = SourceOp;
4199 // Give up as soon as a source operand does not match the existing root value.
4200 if (RootVec != SourceOp)
4201 return nullptr;
4203 // The element must be coming from the same lane in the source vector
4204 // (although it may have crossed lanes in intermediate shuffles).
4205 if (RootElt != DestElt)
4206 return nullptr;
4208 return RootVec;
4211 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4212 Type *RetTy, const SimplifyQuery &Q,
4213 unsigned MaxRecurse) {
4214 if (isa<UndefValue>(Mask))
4215 return UndefValue::get(RetTy);
4217 Type *InVecTy = Op0->getType();
4218 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4219 unsigned InVecNumElts = InVecTy->getVectorNumElements();
4221 SmallVector<int, 32> Indices;
4222 ShuffleVectorInst::getShuffleMask(Mask, Indices);
4223 assert(MaskNumElts == Indices.size() &&
4224 "Size of Indices not same as number of mask elements?");
4226 // Canonicalization: If mask does not select elements from an input vector,
4227 // replace that input vector with undef.
4228 bool MaskSelects0 = false, MaskSelects1 = false;
4229 for (unsigned i = 0; i != MaskNumElts; ++i) {
4230 if (Indices[i] == -1)
4231 continue;
4232 if ((unsigned)Indices[i] < InVecNumElts)
4233 MaskSelects0 = true;
4234 else
4235 MaskSelects1 = true;
4237 if (!MaskSelects0)
4238 Op0 = UndefValue::get(InVecTy);
4239 if (!MaskSelects1)
4240 Op1 = UndefValue::get(InVecTy);
4242 auto *Op0Const = dyn_cast<Constant>(Op0);
4243 auto *Op1Const = dyn_cast<Constant>(Op1);
4245 // If all operands are constant, constant fold the shuffle.
4246 if (Op0Const && Op1Const)
4247 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4249 // Canonicalization: if only one input vector is constant, it shall be the
4250 // second one.
4251 if (Op0Const && !Op1Const) {
4252 std::swap(Op0, Op1);
4253 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4256 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4257 // value type is same as the input vectors' type.
4258 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4259 if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4260 OpShuf->getMask()->getSplatValue())
4261 return Op0;
4263 // Don't fold a shuffle with undef mask elements. This may get folded in a
4264 // better way using demanded bits or other analysis.
4265 // TODO: Should we allow this?
4266 if (find(Indices, -1) != Indices.end())
4267 return nullptr;
4269 // Check if every element of this shuffle can be mapped back to the
4270 // corresponding element of a single root vector. If so, we don't need this
4271 // shuffle. This handles simple identity shuffles as well as chains of
4272 // shuffles that may widen/narrow and/or move elements across lanes and back.
4273 Value *RootVec = nullptr;
4274 for (unsigned i = 0; i != MaskNumElts; ++i) {
4275 // Note that recursion is limited for each vector element, so if any element
4276 // exceeds the limit, this will fail to simplify.
4277 RootVec =
4278 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4280 // We can't replace a widening/narrowing shuffle with one of its operands.
4281 if (!RootVec || RootVec->getType() != RetTy)
4282 return nullptr;
4284 return RootVec;
4287 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4288 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4289 Type *RetTy, const SimplifyQuery &Q) {
4290 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4293 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4294 Value *&Op, const SimplifyQuery &Q) {
4295 if (auto *C = dyn_cast<Constant>(Op))
4296 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4297 return nullptr;
4300 /// Given the operand for an FNeg, see if we can fold the result. If not, this
4301 /// returns null.
4302 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4303 const SimplifyQuery &Q, unsigned MaxRecurse) {
4304 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4305 return C;
4307 Value *X;
4308 // fneg (fneg X) ==> X
4309 if (match(Op, m_FNeg(m_Value(X))))
4310 return X;
4312 return nullptr;
4315 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4316 const SimplifyQuery &Q) {
4317 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4320 static Constant *propagateNaN(Constant *In) {
4321 // If the input is a vector with undef elements, just return a default NaN.
4322 if (!In->isNaN())
4323 return ConstantFP::getNaN(In->getType());
4325 // Propagate the existing NaN constant when possible.
4326 // TODO: Should we quiet a signaling NaN?
4327 return In;
4330 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4331 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4332 return ConstantFP::getNaN(Op0->getType());
4334 if (match(Op0, m_NaN()))
4335 return propagateNaN(cast<Constant>(Op0));
4336 if (match(Op1, m_NaN()))
4337 return propagateNaN(cast<Constant>(Op1));
4339 return nullptr;
4342 /// Given operands for an FAdd, see if we can fold the result. If not, this
4343 /// returns null.
4344 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4345 const SimplifyQuery &Q, unsigned MaxRecurse) {
4346 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4347 return C;
4349 if (Constant *C = simplifyFPBinop(Op0, Op1))
4350 return C;
4352 // fadd X, -0 ==> X
4353 if (match(Op1, m_NegZeroFP()))
4354 return Op0;
4356 // fadd X, 0 ==> X, when we know X is not -0
4357 if (match(Op1, m_PosZeroFP()) &&
4358 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4359 return Op0;
4361 // With nnan: -X + X --> 0.0 (and commuted variant)
4362 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4363 // Negative zeros are allowed because we always end up with positive zero:
4364 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4365 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4366 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4367 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4368 if (FMF.noNaNs()) {
4369 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4370 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4371 return ConstantFP::getNullValue(Op0->getType());
4373 if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4374 match(Op1, m_FNeg(m_Specific(Op0))))
4375 return ConstantFP::getNullValue(Op0->getType());
4378 // (X - Y) + Y --> X
4379 // Y + (X - Y) --> X
4380 Value *X;
4381 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4382 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4383 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4384 return X;
4386 return nullptr;
4389 /// Given operands for an FSub, see if we can fold the result. If not, this
4390 /// returns null.
4391 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4392 const SimplifyQuery &Q, unsigned MaxRecurse) {
4393 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4394 return C;
4396 if (Constant *C = simplifyFPBinop(Op0, Op1))
4397 return C;
4399 // fsub X, +0 ==> X
4400 if (match(Op1, m_PosZeroFP()))
4401 return Op0;
4403 // fsub X, -0 ==> X, when we know X is not -0
4404 if (match(Op1, m_NegZeroFP()) &&
4405 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4406 return Op0;
4408 // fsub -0.0, (fsub -0.0, X) ==> X
4409 // fsub -0.0, (fneg X) ==> X
4410 Value *X;
4411 if (match(Op0, m_NegZeroFP()) &&
4412 match(Op1, m_FNeg(m_Value(X))))
4413 return X;
4415 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4416 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4417 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4418 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4419 match(Op1, m_FNeg(m_Value(X)))))
4420 return X;
4422 // fsub nnan x, x ==> 0.0
4423 if (FMF.noNaNs() && Op0 == Op1)
4424 return Constant::getNullValue(Op0->getType());
4426 // Y - (Y - X) --> X
4427 // (X + Y) - Y --> X
4428 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4429 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4430 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4431 return X;
4433 return nullptr;
4436 /// Given the operands for an FMul, see if we can fold the result
4437 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4438 const SimplifyQuery &Q, unsigned MaxRecurse) {
4439 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4440 return C;
4442 if (Constant *C = simplifyFPBinop(Op0, Op1))
4443 return C;
4445 // fmul X, 1.0 ==> X
4446 if (match(Op1, m_FPOne()))
4447 return Op0;
4449 // fmul nnan nsz X, 0 ==> 0
4450 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4451 return ConstantFP::getNullValue(Op0->getType());
4453 // sqrt(X) * sqrt(X) --> X, if we can:
4454 // 1. Remove the intermediate rounding (reassociate).
4455 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4456 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4457 Value *X;
4458 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4459 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4460 return X;
4462 return nullptr;
4465 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4466 const SimplifyQuery &Q) {
4467 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4471 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4472 const SimplifyQuery &Q) {
4473 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4476 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4477 const SimplifyQuery &Q) {
4478 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4481 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4482 const SimplifyQuery &Q, unsigned) {
4483 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4484 return C;
4486 if (Constant *C = simplifyFPBinop(Op0, Op1))
4487 return C;
4489 // X / 1.0 -> X
4490 if (match(Op1, m_FPOne()))
4491 return Op0;
4493 // 0 / X -> 0
4494 // Requires that NaNs are off (X could be zero) and signed zeroes are
4495 // ignored (X could be positive or negative, so the output sign is unknown).
4496 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4497 return ConstantFP::getNullValue(Op0->getType());
4499 if (FMF.noNaNs()) {
4500 // X / X -> 1.0 is legal when NaNs are ignored.
4501 // We can ignore infinities because INF/INF is NaN.
4502 if (Op0 == Op1)
4503 return ConstantFP::get(Op0->getType(), 1.0);
4505 // (X * Y) / Y --> X if we can reassociate to the above form.
4506 Value *X;
4507 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4508 return X;
4510 // -X / X -> -1.0 and
4511 // X / -X -> -1.0 are legal when NaNs are ignored.
4512 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4513 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4514 match(Op1, m_FNegNSZ(m_Specific(Op0))))
4515 return ConstantFP::get(Op0->getType(), -1.0);
4518 return nullptr;
4521 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4522 const SimplifyQuery &Q) {
4523 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4526 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4527 const SimplifyQuery &Q, unsigned) {
4528 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4529 return C;
4531 if (Constant *C = simplifyFPBinop(Op0, Op1))
4532 return C;
4534 // Unlike fdiv, the result of frem always matches the sign of the dividend.
4535 // The constant match may include undef elements in a vector, so return a full
4536 // zero constant as the result.
4537 if (FMF.noNaNs()) {
4538 // +0 % X -> 0
4539 if (match(Op0, m_PosZeroFP()))
4540 return ConstantFP::getNullValue(Op0->getType());
4541 // -0 % X -> -0
4542 if (match(Op0, m_NegZeroFP()))
4543 return ConstantFP::getNegativeZero(Op0->getType());
4546 return nullptr;
4549 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4550 const SimplifyQuery &Q) {
4551 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4554 //=== Helper functions for higher up the class hierarchy.
4556 /// Given the operand for a UnaryOperator, see if we can fold the result.
4557 /// If not, this returns null.
4558 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
4559 unsigned MaxRecurse) {
4560 switch (Opcode) {
4561 case Instruction::FNeg:
4562 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
4563 default:
4564 llvm_unreachable("Unexpected opcode");
4568 /// Given the operand for a UnaryOperator, see if we can fold the result.
4569 /// If not, this returns null.
4570 /// Try to use FastMathFlags when folding the result.
4571 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
4572 const FastMathFlags &FMF,
4573 const SimplifyQuery &Q, unsigned MaxRecurse) {
4574 switch (Opcode) {
4575 case Instruction::FNeg:
4576 return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
4577 default:
4578 return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
4582 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
4583 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
4586 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
4587 const SimplifyQuery &Q) {
4588 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
4591 /// Given operands for a BinaryOperator, see if we can fold the result.
4592 /// If not, this returns null.
4593 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4594 const SimplifyQuery &Q, unsigned MaxRecurse) {
4595 switch (Opcode) {
4596 case Instruction::Add:
4597 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4598 case Instruction::Sub:
4599 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4600 case Instruction::Mul:
4601 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4602 case Instruction::SDiv:
4603 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4604 case Instruction::UDiv:
4605 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4606 case Instruction::SRem:
4607 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4608 case Instruction::URem:
4609 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4610 case Instruction::Shl:
4611 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4612 case Instruction::LShr:
4613 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4614 case Instruction::AShr:
4615 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4616 case Instruction::And:
4617 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4618 case Instruction::Or:
4619 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4620 case Instruction::Xor:
4621 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4622 case Instruction::FAdd:
4623 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4624 case Instruction::FSub:
4625 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4626 case Instruction::FMul:
4627 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4628 case Instruction::FDiv:
4629 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4630 case Instruction::FRem:
4631 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4632 default:
4633 llvm_unreachable("Unexpected opcode");
4637 /// Given operands for a BinaryOperator, see if we can fold the result.
4638 /// If not, this returns null.
4639 /// Try to use FastMathFlags when folding the result.
4640 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4641 const FastMathFlags &FMF, const SimplifyQuery &Q,
4642 unsigned MaxRecurse) {
4643 switch (Opcode) {
4644 case Instruction::FAdd:
4645 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4646 case Instruction::FSub:
4647 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4648 case Instruction::FMul:
4649 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4650 case Instruction::FDiv:
4651 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
4652 default:
4653 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4657 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4658 const SimplifyQuery &Q) {
4659 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4662 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4663 FastMathFlags FMF, const SimplifyQuery &Q) {
4664 return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4667 /// Given operands for a CmpInst, see if we can fold the result.
4668 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4669 const SimplifyQuery &Q, unsigned MaxRecurse) {
4670 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4671 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4672 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4675 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4676 const SimplifyQuery &Q) {
4677 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4680 static bool IsIdempotent(Intrinsic::ID ID) {
4681 switch (ID) {
4682 default: return false;
4684 // Unary idempotent: f(f(x)) = f(x)
4685 case Intrinsic::fabs:
4686 case Intrinsic::floor:
4687 case Intrinsic::ceil:
4688 case Intrinsic::trunc:
4689 case Intrinsic::rint:
4690 case Intrinsic::nearbyint:
4691 case Intrinsic::round:
4692 case Intrinsic::canonicalize:
4693 return true;
4697 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4698 const DataLayout &DL) {
4699 GlobalValue *PtrSym;
4700 APInt PtrOffset;
4701 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4702 return nullptr;
4704 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4705 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4706 Type *Int32PtrTy = Int32Ty->getPointerTo();
4707 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4709 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4710 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4711 return nullptr;
4713 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4714 if (OffsetInt % 4 != 0)
4715 return nullptr;
4717 Constant *C = ConstantExpr::getGetElementPtr(
4718 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4719 ConstantInt::get(Int64Ty, OffsetInt / 4));
4720 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4721 if (!Loaded)
4722 return nullptr;
4724 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4725 if (!LoadedCE)
4726 return nullptr;
4728 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4729 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4730 if (!LoadedCE)
4731 return nullptr;
4734 if (LoadedCE->getOpcode() != Instruction::Sub)
4735 return nullptr;
4737 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4738 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4739 return nullptr;
4740 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4742 Constant *LoadedRHS = LoadedCE->getOperand(1);
4743 GlobalValue *LoadedRHSSym;
4744 APInt LoadedRHSOffset;
4745 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4746 DL) ||
4747 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4748 return nullptr;
4750 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4753 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4754 const SimplifyQuery &Q) {
4755 // Idempotent functions return the same result when called repeatedly.
4756 Intrinsic::ID IID = F->getIntrinsicID();
4757 if (IsIdempotent(IID))
4758 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4759 if (II->getIntrinsicID() == IID)
4760 return II;
4762 Value *X;
4763 switch (IID) {
4764 case Intrinsic::fabs:
4765 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4766 break;
4767 case Intrinsic::bswap:
4768 // bswap(bswap(x)) -> x
4769 if (match(Op0, m_BSwap(m_Value(X)))) return X;
4770 break;
4771 case Intrinsic::bitreverse:
4772 // bitreverse(bitreverse(x)) -> x
4773 if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4774 break;
4775 case Intrinsic::exp:
4776 // exp(log(x)) -> x
4777 if (Q.CxtI->hasAllowReassoc() &&
4778 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4779 break;
4780 case Intrinsic::exp2:
4781 // exp2(log2(x)) -> x
4782 if (Q.CxtI->hasAllowReassoc() &&
4783 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4784 break;
4785 case Intrinsic::log:
4786 // log(exp(x)) -> x
4787 if (Q.CxtI->hasAllowReassoc() &&
4788 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4789 break;
4790 case Intrinsic::log2:
4791 // log2(exp2(x)) -> x
4792 if (Q.CxtI->hasAllowReassoc() &&
4793 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4794 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4795 m_Value(X))))) return X;
4796 break;
4797 case Intrinsic::log10:
4798 // log10(pow(10.0, x)) -> x
4799 if (Q.CxtI->hasAllowReassoc() &&
4800 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4801 m_Value(X)))) return X;
4802 break;
4803 case Intrinsic::floor:
4804 case Intrinsic::trunc:
4805 case Intrinsic::ceil:
4806 case Intrinsic::round:
4807 case Intrinsic::nearbyint:
4808 case Intrinsic::rint: {
4809 // floor (sitofp x) -> sitofp x
4810 // floor (uitofp x) -> uitofp x
4812 // Converting from int always results in a finite integral number or
4813 // infinity. For either of those inputs, these rounding functions always
4814 // return the same value, so the rounding can be eliminated.
4815 if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
4816 return Op0;
4817 break;
4819 default:
4820 break;
4823 return nullptr;
4826 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
4827 const SimplifyQuery &Q) {
4828 Intrinsic::ID IID = F->getIntrinsicID();
4829 Type *ReturnType = F->getReturnType();
4830 switch (IID) {
4831 case Intrinsic::usub_with_overflow:
4832 case Intrinsic::ssub_with_overflow:
4833 // X - X -> { 0, false }
4834 if (Op0 == Op1)
4835 return Constant::getNullValue(ReturnType);
4836 LLVM_FALLTHROUGH;
4837 case Intrinsic::uadd_with_overflow:
4838 case Intrinsic::sadd_with_overflow:
4839 // X - undef -> { undef, false }
4840 // undef - X -> { undef, false }
4841 // X + undef -> { undef, false }
4842 // undef + x -> { undef, false }
4843 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) {
4844 return ConstantStruct::get(
4845 cast<StructType>(ReturnType),
4846 {UndefValue::get(ReturnType->getStructElementType(0)),
4847 Constant::getNullValue(ReturnType->getStructElementType(1))});
4849 break;
4850 case Intrinsic::umul_with_overflow:
4851 case Intrinsic::smul_with_overflow:
4852 // 0 * X -> { 0, false }
4853 // X * 0 -> { 0, false }
4854 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
4855 return Constant::getNullValue(ReturnType);
4856 // undef * X -> { 0, false }
4857 // X * undef -> { 0, false }
4858 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4859 return Constant::getNullValue(ReturnType);
4860 break;
4861 case Intrinsic::uadd_sat:
4862 // sat(MAX + X) -> MAX
4863 // sat(X + MAX) -> MAX
4864 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
4865 return Constant::getAllOnesValue(ReturnType);
4866 LLVM_FALLTHROUGH;
4867 case Intrinsic::sadd_sat:
4868 // sat(X + undef) -> -1
4869 // sat(undef + X) -> -1
4870 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
4871 // For signed: Assume undef is ~X, in which case X + ~X = -1.
4872 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4873 return Constant::getAllOnesValue(ReturnType);
4875 // X + 0 -> X
4876 if (match(Op1, m_Zero()))
4877 return Op0;
4878 // 0 + X -> X
4879 if (match(Op0, m_Zero()))
4880 return Op1;
4881 break;
4882 case Intrinsic::usub_sat:
4883 // sat(0 - X) -> 0, sat(X - MAX) -> 0
4884 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
4885 return Constant::getNullValue(ReturnType);
4886 LLVM_FALLTHROUGH;
4887 case Intrinsic::ssub_sat:
4888 // X - X -> 0, X - undef -> 0, undef - X -> 0
4889 if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
4890 return Constant::getNullValue(ReturnType);
4891 // X - 0 -> X
4892 if (match(Op1, m_Zero()))
4893 return Op0;
4894 break;
4895 case Intrinsic::load_relative:
4896 if (auto *C0 = dyn_cast<Constant>(Op0))
4897 if (auto *C1 = dyn_cast<Constant>(Op1))
4898 return SimplifyRelativeLoad(C0, C1, Q.DL);
4899 break;
4900 case Intrinsic::powi:
4901 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
4902 // powi(x, 0) -> 1.0
4903 if (Power->isZero())
4904 return ConstantFP::get(Op0->getType(), 1.0);
4905 // powi(x, 1) -> x
4906 if (Power->isOne())
4907 return Op0;
4909 break;
4910 case Intrinsic::maxnum:
4911 case Intrinsic::minnum:
4912 case Intrinsic::maximum:
4913 case Intrinsic::minimum: {
4914 // If the arguments are the same, this is a no-op.
4915 if (Op0 == Op1) return Op0;
4917 // If one argument is undef, return the other argument.
4918 if (match(Op0, m_Undef()))
4919 return Op1;
4920 if (match(Op1, m_Undef()))
4921 return Op0;
4923 // If one argument is NaN, return other or NaN appropriately.
4924 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
4925 if (match(Op0, m_NaN()))
4926 return PropagateNaN ? Op0 : Op1;
4927 if (match(Op1, m_NaN()))
4928 return PropagateNaN ? Op1 : Op0;
4930 // Min/max of the same operation with common operand:
4931 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
4932 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
4933 if (M0->getIntrinsicID() == IID &&
4934 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
4935 return Op0;
4936 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
4937 if (M1->getIntrinsicID() == IID &&
4938 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
4939 return Op1;
4941 // min(X, -Inf) --> -Inf (and commuted variant)
4942 // max(X, +Inf) --> +Inf (and commuted variant)
4943 bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
4944 const APFloat *C;
4945 if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
4946 C->isNegative() == UseNegInf) ||
4947 (match(Op1, m_APFloat(C)) && C->isInfinity() &&
4948 C->isNegative() == UseNegInf))
4949 return ConstantFP::getInfinity(ReturnType, UseNegInf);
4951 // TODO: minnum(nnan x, inf) -> x
4952 // TODO: minnum(nnan ninf x, flt_max) -> x
4953 // TODO: maxnum(nnan x, -inf) -> x
4954 // TODO: maxnum(nnan ninf x, -flt_max) -> x
4955 break;
4957 default:
4958 break;
4961 return nullptr;
4964 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
4966 // Intrinsics with no operands have some kind of side effect. Don't simplify.
4967 unsigned NumOperands = Call->getNumArgOperands();
4968 if (!NumOperands)
4969 return nullptr;
4971 Function *F = cast<Function>(Call->getCalledFunction());
4972 Intrinsic::ID IID = F->getIntrinsicID();
4973 if (NumOperands == 1)
4974 return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
4976 if (NumOperands == 2)
4977 return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
4978 Call->getArgOperand(1), Q);
4980 // Handle intrinsics with 3 or more arguments.
4981 switch (IID) {
4982 case Intrinsic::masked_load:
4983 case Intrinsic::masked_gather: {
4984 Value *MaskArg = Call->getArgOperand(2);
4985 Value *PassthruArg = Call->getArgOperand(3);
4986 // If the mask is all zeros or undef, the "passthru" argument is the result.
4987 if (maskIsAllZeroOrUndef(MaskArg))
4988 return PassthruArg;
4989 return nullptr;
4991 case Intrinsic::fshl:
4992 case Intrinsic::fshr: {
4993 Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
4994 *ShAmtArg = Call->getArgOperand(2);
4996 // If both operands are undef, the result is undef.
4997 if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
4998 return UndefValue::get(F->getReturnType());
5000 // If shift amount is undef, assume it is zero.
5001 if (match(ShAmtArg, m_Undef()))
5002 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5004 const APInt *ShAmtC;
5005 if (match(ShAmtArg, m_APInt(ShAmtC))) {
5006 // If there's effectively no shift, return the 1st arg or 2nd arg.
5007 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5008 if (ShAmtC->urem(BitWidth).isNullValue())
5009 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5011 return nullptr;
5013 default:
5014 return nullptr;
5018 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5019 Value *Callee = Call->getCalledValue();
5021 // call undef -> undef
5022 // call null -> undef
5023 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
5024 return UndefValue::get(Call->getType());
5026 Function *F = dyn_cast<Function>(Callee);
5027 if (!F)
5028 return nullptr;
5030 if (F->isIntrinsic())
5031 if (Value *Ret = simplifyIntrinsic(Call, Q))
5032 return Ret;
5034 if (!canConstantFoldCallTo(Call, F))
5035 return nullptr;
5037 SmallVector<Constant *, 4> ConstantArgs;
5038 unsigned NumArgs = Call->getNumArgOperands();
5039 ConstantArgs.reserve(NumArgs);
5040 for (auto &Arg : Call->args()) {
5041 Constant *C = dyn_cast<Constant>(&Arg);
5042 if (!C)
5043 return nullptr;
5044 ConstantArgs.push_back(C);
5047 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5050 /// See if we can compute a simplified version of this instruction.
5051 /// If not, this returns null.
5053 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5054 OptimizationRemarkEmitter *ORE) {
5055 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5056 Value *Result;
5058 switch (I->getOpcode()) {
5059 default:
5060 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5061 break;
5062 case Instruction::FNeg:
5063 Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5064 break;
5065 case Instruction::FAdd:
5066 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5067 I->getFastMathFlags(), Q);
5068 break;
5069 case Instruction::Add:
5070 Result =
5071 SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5072 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5073 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5074 break;
5075 case Instruction::FSub:
5076 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5077 I->getFastMathFlags(), Q);
5078 break;
5079 case Instruction::Sub:
5080 Result =
5081 SimplifySubInst(I->getOperand(0), I->getOperand(1),
5082 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5083 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5084 break;
5085 case Instruction::FMul:
5086 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5087 I->getFastMathFlags(), Q);
5088 break;
5089 case Instruction::Mul:
5090 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5091 break;
5092 case Instruction::SDiv:
5093 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5094 break;
5095 case Instruction::UDiv:
5096 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5097 break;
5098 case Instruction::FDiv:
5099 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5100 I->getFastMathFlags(), Q);
5101 break;
5102 case Instruction::SRem:
5103 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5104 break;
5105 case Instruction::URem:
5106 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5107 break;
5108 case Instruction::FRem:
5109 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5110 I->getFastMathFlags(), Q);
5111 break;
5112 case Instruction::Shl:
5113 Result =
5114 SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5115 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5116 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5117 break;
5118 case Instruction::LShr:
5119 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5120 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5121 break;
5122 case Instruction::AShr:
5123 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5124 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5125 break;
5126 case Instruction::And:
5127 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5128 break;
5129 case Instruction::Or:
5130 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5131 break;
5132 case Instruction::Xor:
5133 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5134 break;
5135 case Instruction::ICmp:
5136 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5137 I->getOperand(0), I->getOperand(1), Q);
5138 break;
5139 case Instruction::FCmp:
5140 Result =
5141 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5142 I->getOperand(1), I->getFastMathFlags(), Q);
5143 break;
5144 case Instruction::Select:
5145 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5146 I->getOperand(2), Q);
5147 break;
5148 case Instruction::GetElementPtr: {
5149 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
5150 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5151 Ops, Q);
5152 break;
5154 case Instruction::InsertValue: {
5155 InsertValueInst *IV = cast<InsertValueInst>(I);
5156 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5157 IV->getInsertedValueOperand(),
5158 IV->getIndices(), Q);
5159 break;
5161 case Instruction::InsertElement: {
5162 auto *IE = cast<InsertElementInst>(I);
5163 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5164 IE->getOperand(2), Q);
5165 break;
5167 case Instruction::ExtractValue: {
5168 auto *EVI = cast<ExtractValueInst>(I);
5169 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5170 EVI->getIndices(), Q);
5171 break;
5173 case Instruction::ExtractElement: {
5174 auto *EEI = cast<ExtractElementInst>(I);
5175 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5176 EEI->getIndexOperand(), Q);
5177 break;
5179 case Instruction::ShuffleVector: {
5180 auto *SVI = cast<ShuffleVectorInst>(I);
5181 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5182 SVI->getMask(), SVI->getType(), Q);
5183 break;
5185 case Instruction::PHI:
5186 Result = SimplifyPHINode(cast<PHINode>(I), Q);
5187 break;
5188 case Instruction::Call: {
5189 Result = SimplifyCall(cast<CallInst>(I), Q);
5190 break;
5192 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5193 #include "llvm/IR/Instruction.def"
5194 #undef HANDLE_CAST_INST
5195 Result =
5196 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5197 break;
5198 case Instruction::Alloca:
5199 // No simplifications for Alloca and it can't be constant folded.
5200 Result = nullptr;
5201 break;
5204 // In general, it is possible for computeKnownBits to determine all bits in a
5205 // value even when the operands are not all constants.
5206 if (!Result && I->getType()->isIntOrIntVectorTy()) {
5207 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
5208 if (Known.isConstant())
5209 Result = ConstantInt::get(I->getType(), Known.getConstant());
5212 /// If called on unreachable code, the above logic may report that the
5213 /// instruction simplified to itself. Make life easier for users by
5214 /// detecting that case here, returning a safe value instead.
5215 return Result == I ? UndefValue::get(I->getType()) : Result;
5218 /// Implementation of recursive simplification through an instruction's
5219 /// uses.
5221 /// This is the common implementation of the recursive simplification routines.
5222 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5223 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5224 /// instructions to process and attempt to simplify it using
5225 /// InstructionSimplify.
5227 /// This routine returns 'true' only when *it* simplifies something. The passed
5228 /// in simplified value does not count toward this.
5229 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
5230 const TargetLibraryInfo *TLI,
5231 const DominatorTree *DT,
5232 AssumptionCache *AC) {
5233 bool Simplified = false;
5234 SmallSetVector<Instruction *, 8> Worklist;
5235 const DataLayout &DL = I->getModule()->getDataLayout();
5237 // If we have an explicit value to collapse to, do that round of the
5238 // simplification loop by hand initially.
5239 if (SimpleV) {
5240 for (User *U : I->users())
5241 if (U != I)
5242 Worklist.insert(cast<Instruction>(U));
5244 // Replace the instruction with its simplified value.
5245 I->replaceAllUsesWith(SimpleV);
5247 // Gracefully handle edge cases where the instruction is not wired into any
5248 // parent block.
5249 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5250 !I->mayHaveSideEffects())
5251 I->eraseFromParent();
5252 } else {
5253 Worklist.insert(I);
5256 // Note that we must test the size on each iteration, the worklist can grow.
5257 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5258 I = Worklist[Idx];
5260 // See if this instruction simplifies.
5261 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
5262 if (!SimpleV)
5263 continue;
5265 Simplified = true;
5267 // Stash away all the uses of the old instruction so we can check them for
5268 // recursive simplifications after a RAUW. This is cheaper than checking all
5269 // uses of To on the recursive step in most cases.
5270 for (User *U : I->users())
5271 Worklist.insert(cast<Instruction>(U));
5273 // Replace the instruction with its simplified value.
5274 I->replaceAllUsesWith(SimpleV);
5276 // Gracefully handle edge cases where the instruction is not wired into any
5277 // parent block.
5278 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5279 !I->mayHaveSideEffects())
5280 I->eraseFromParent();
5282 return Simplified;
5285 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5286 const TargetLibraryInfo *TLI,
5287 const DominatorTree *DT,
5288 AssumptionCache *AC) {
5289 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
5292 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
5293 const TargetLibraryInfo *TLI,
5294 const DominatorTree *DT,
5295 AssumptionCache *AC) {
5296 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5297 assert(SimpleV && "Must provide a simplified value.");
5298 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
5301 namespace llvm {
5302 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5303 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5304 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5305 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5306 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5307 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5308 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5309 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5312 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5313 const DataLayout &DL) {
5314 return {DL, &AR.TLI, &AR.DT, &AR.AC};
5317 template <class T, class... TArgs>
5318 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5319 Function &F) {
5320 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5321 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5322 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5323 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5325 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5326 Function &);