LLVM 24.0.0git
InstructionSimplify.cpp
Go to the documentation of this file.
1//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements routines for folding instructions into simpler forms
10// that do not require creating new instructions. This does constant folding
11// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14// simplified: This is usually true and assuming it simplifies the logic (if
15// they have not been simplified then results are correct but maybe suboptimal).
16//
17//===----------------------------------------------------------------------===//
18
20
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/Loads.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Dominators.h"
42#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/IntrinsicsAArch64.h"
45#include "llvm/IR/Operator.h"
47#include "llvm/IR/Statepoint.h"
50#include <algorithm>
51#include <optional>
52using namespace llvm;
53using namespace llvm::PatternMatch;
54
55#define DEBUG_TYPE "instsimplify"
56
57enum { RecursionLimit = 3 };
58
59STATISTIC(NumExpand, "Number of expansions");
60STATISTIC(NumReassoc, "Number of reassociations");
61
62static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
63 unsigned);
64static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
65static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
66 const SimplifyQuery &, unsigned);
67static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
68 unsigned);
69static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
70 const SimplifyQuery &, unsigned);
72 const SimplifyQuery &, unsigned);
74 const SimplifyQuery &Q, unsigned MaxRecurse);
75static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
76static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
77 unsigned);
78static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
79 unsigned);
81 GEPNoWrapFlags, const SimplifyQuery &, unsigned);
82static Value *
84 const SimplifyQuery &,
85 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned);
87 Instruction *I, ArrayRef<Value *> NewOps, const SimplifyQuery &SQ,
88 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned MaxRecurse);
89
90/// For a boolean type or a vector of boolean type, return false or a vector
91/// with every element false.
92static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
93
94/// For a boolean type or a vector of boolean type, return true or a vector
95/// with every element true.
96static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
97
98/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
101 if (!Cmp)
102 return false;
103 CmpInst::Predicate CPred = Cmp->getPredicate();
104 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
105 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
106 return true;
107 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
108 CRHS == LHS;
109}
110
111/// Simplify comparison with true or false branch of select:
112/// %sel = select i1 %cond, i32 %tv, i32 %fv
113/// %cmp = icmp sle i32 %sel, %rhs
114/// Compose new comparison by substituting %sel with either %tv or %fv
115/// and see if it simplifies.
117 Value *Cond, const SimplifyQuery &Q,
118 unsigned MaxRecurse, Constant *TrueOrFalse) {
119 Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
120 if (SimplifiedCmp == Cond) {
121 // %cmp simplified to the select condition (%cond).
122 return TrueOrFalse;
123 } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
124 // It didn't simplify. However, if composed comparison is equivalent
125 // to the select condition (%cond) then we can replace it.
126 return TrueOrFalse;
127 }
128 return SimplifiedCmp;
129}
130
131/// Simplify comparison with true branch of select
133 Value *Cond, const SimplifyQuery &Q,
134 unsigned MaxRecurse) {
135 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
136 getTrue(Cond->getType()));
137}
138
139/// Simplify comparison with false branch of select
141 Value *Cond, const SimplifyQuery &Q,
142 unsigned MaxRecurse) {
143 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
144 getFalse(Cond->getType()));
145}
146
147/// We know comparison with both branches of select can be simplified, but they
148/// are not equal. This routine handles some logical simplifications.
150 Value *Cond,
151 const SimplifyQuery &Q,
152 unsigned MaxRecurse) {
153 // If the false value simplified to false, then the result of the compare
154 // is equal to "Cond && TCmp". This also catches the case when the false
155 // value simplified to false and the true value to true, returning "Cond".
156 // Folding select to and/or isn't poison-safe in general; impliesPoison
157 // checks whether folding it does not convert a well-defined value into
158 // poison.
159 if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
160 if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
161 return V;
162 // If the true value simplified to true, then the result of the compare
163 // is equal to "Cond || FCmp".
164 if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
165 if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
166 return V;
167 // Finally, if the false value simplified to true and the true value to
168 // false, then the result of the compare is equal to "!Cond".
169 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
170 if (Value *V = simplifyXorInst(
171 Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
172 return V;
173 return nullptr;
174}
175
176/// Does the given value dominate the specified phi node?
177static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
179 if (!I)
180 // Arguments and constants dominate all instructions.
181 return true;
182
183 // If we have a DominatorTree then do a precise test.
184 if (DT)
185 return DT->dominates(I, P);
186
187 // Otherwise, if the instruction is in the entry block and is not an invoke,
188 // then it obviously dominates all phi nodes.
189 if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
191 return true;
192
193 return false;
194}
195
196/// Try to simplify a binary operator of form "V op OtherOp" where V is
197/// "(B0 opex B1)" by distributing 'op' across 'opex' as
198/// "(B0 op OtherOp) opex (B1 op OtherOp)".
200 Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
201 const SimplifyQuery &Q, unsigned MaxRecurse) {
203 if (!B || B->getOpcode() != OpcodeToExpand)
204 return nullptr;
205 Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
206 Value *L =
207 simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
208 if (!L)
209 return nullptr;
210 Value *R =
211 simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
212 if (!R)
213 return nullptr;
214
215 // Does the expanded pair of binops simplify to the existing binop?
216 if ((L == B0 && R == B1) ||
217 (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
218 ++NumExpand;
219 return B;
220 }
221
222 // Otherwise, return "L op' R" if it simplifies.
223 Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
224 if (!S)
225 return nullptr;
226
227 ++NumExpand;
228 return S;
229}
230
231/// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
232/// distributing op over op'.
234 Value *R,
235 Instruction::BinaryOps OpcodeToExpand,
236 const SimplifyQuery &Q,
237 unsigned MaxRecurse) {
238 // Recursion is always used, so bail out at once if we already hit the limit.
239 if (!MaxRecurse--)
240 return nullptr;
241
242 if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
243 return V;
244 if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
245 return V;
246 return nullptr;
247}
248
249/// Generic simplifications for associative binary operations.
250/// Returns the simpler value, or null if none was found.
252 Value *LHS, Value *RHS,
253 const SimplifyQuery &Q,
254 unsigned MaxRecurse) {
255 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
256
257 // Recursion is always used, so bail out at once if we already hit the limit.
258 if (!MaxRecurse--)
259 return nullptr;
260
263
264 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
265 if (Op0 && Op0->getOpcode() == Opcode) {
266 Value *A = Op0->getOperand(0);
267 Value *B = Op0->getOperand(1);
268 Value *C = RHS;
269
270 // Does "B op C" simplify?
271 if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
272 // It does! Return "A op V" if it simplifies or is already available.
273 // If V equals B then "A op V" is just the LHS.
274 if (V == B)
275 return LHS;
276 // Otherwise return "A op V" if it simplifies.
277 if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
278 ++NumReassoc;
279 return W;
280 }
281 }
282 }
283
284 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
285 if (Op1 && Op1->getOpcode() == Opcode) {
286 Value *A = LHS;
287 Value *B = Op1->getOperand(0);
288 Value *C = Op1->getOperand(1);
289
290 // Does "A op B" simplify?
291 if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
292 // It does! Return "V op C" if it simplifies or is already available.
293 // If V equals B then "V op C" is just the RHS.
294 if (V == B)
295 return RHS;
296 // Otherwise return "V op C" if it simplifies.
297 if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
298 ++NumReassoc;
299 return W;
300 }
301 }
302 }
303
304 // The remaining transforms require commutativity as well as associativity.
305 if (!Instruction::isCommutative(Opcode))
306 return nullptr;
307
308 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
309 if (Op0 && Op0->getOpcode() == Opcode) {
310 Value *A = Op0->getOperand(0);
311 Value *B = Op0->getOperand(1);
312 Value *C = RHS;
313
314 // Does "C op A" simplify?
315 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
316 // It does! Return "V op B" if it simplifies or is already available.
317 // If V equals A then "V op B" is just the LHS.
318 if (V == A)
319 return LHS;
320 // Otherwise return "V op B" if it simplifies.
321 if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
322 ++NumReassoc;
323 return W;
324 }
325 }
326 }
327
328 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
329 if (Op1 && Op1->getOpcode() == Opcode) {
330 Value *A = LHS;
331 Value *B = Op1->getOperand(0);
332 Value *C = Op1->getOperand(1);
333
334 // Does "C op A" simplify?
335 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
336 // It does! Return "B op V" if it simplifies or is already available.
337 // If V equals C then "B op V" is just the RHS.
338 if (V == C)
339 return RHS;
340 // Otherwise return "B op V" if it simplifies.
341 if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
342 ++NumReassoc;
343 return W;
344 }
345 }
346 }
347
348 return nullptr;
349}
350
351/// In the case of a binary operation with a select instruction as an operand,
352/// try to simplify the binop by seeing whether evaluating it on both branches
353/// of the select results in the same value. Returns the common value if so,
354/// otherwise returns null.
356 Value *RHS, const SimplifyQuery &Q,
357 unsigned MaxRecurse) {
358 // Recursion is always used, so bail out at once if we already hit the limit.
359 if (!MaxRecurse--)
360 return nullptr;
361
362 SelectInst *SI;
363 if (isa<SelectInst>(LHS)) {
365 } else {
366 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
368 }
369
370 // Evaluate the BinOp on the true and false branches of the select.
371 Value *TV;
372 Value *FV;
373 if (SI == LHS) {
374 TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
375 FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
376 } else {
377 TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
378 FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
379 }
380
381 // If they simplified to the same value, then return the common value.
382 // If they both failed to simplify then return null.
383 if (TV == FV)
384 return TV;
385
386 // If one branch simplified to undef, return the other one.
387 if (TV && Q.isUndefValue(TV))
388 return FV;
389 if (FV && Q.isUndefValue(FV))
390 return TV;
391
392 // If applying the operation did not change the true and false select values,
393 // then the result of the binop is the select itself.
394 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
395 return SI;
396
397 // If one branch simplified and the other did not, and the simplified
398 // value is equal to the unsimplified one, return the simplified value.
399 // For example, select (cond, X, X & Z) & Z -> X & Z.
400 if ((FV && !TV) || (TV && !FV)) {
401 // Check that the simplified value has the form "X op Y" where "op" is the
402 // same as the original operation.
403 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
404 if (Simplified && Simplified->getOpcode() == unsigned(Opcode) &&
405 !Simplified->hasPoisonGeneratingFlags()) {
406 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
407 // We already know that "op" is the same as for the simplified value. See
408 // if the operands match too. If so, return the simplified value.
409 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
410 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
411 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
412 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
413 Simplified->getOperand(1) == UnsimplifiedRHS)
414 return Simplified;
415 if (Simplified->isCommutative() &&
416 Simplified->getOperand(1) == UnsimplifiedLHS &&
417 Simplified->getOperand(0) == UnsimplifiedRHS)
418 return Simplified;
419 }
420 }
421
422 return nullptr;
423}
424
425/// In the case of a comparison with a select instruction, try to simplify the
426/// comparison by seeing whether both branches of the select result in the same
427/// value. Returns the common value if so, otherwise returns null.
428/// For example, if we have:
429/// %tmp = select i1 %cmp, i32 1, i32 2
430/// %cmp1 = icmp sle i32 %tmp, 3
431/// We can simplify %cmp1 to true, because both branches of select are
432/// less than 3. We compose new comparison by substituting %tmp with both
433/// branches of select and see if it can be simplified.
435 const SimplifyQuery &Q, unsigned MaxRecurse) {
436 // Recursion is always used, so bail out at once if we already hit the limit.
437 if (!MaxRecurse--)
438 return nullptr;
439
440 // Make sure the select is on the LHS.
441 if (!isa<SelectInst>(LHS)) {
442 std::swap(LHS, RHS);
444 }
445 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
447 Value *Cond = SI->getCondition();
448 Value *TV = SI->getTrueValue();
449 Value *FV = SI->getFalseValue();
450
451 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
452 // Does "cmp TV, RHS" simplify?
453 Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
454 if (!TCmp)
455 return nullptr;
456
457 // Does "cmp FV, RHS" simplify?
458 Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
459 if (!FCmp)
460 return nullptr;
461
462 // If both sides simplified to the same value, then use it as the result of
463 // the original comparison.
464 if (TCmp == FCmp)
465 return TCmp;
466
467 // The remaining cases only make sense if the select condition has the same
468 // type as the result of the comparison, so bail out if this is not so.
469 if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
470 return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
471
472 return nullptr;
473}
474
475/// In the case of a binary operation with an operand that is a PHI instruction,
476/// try to simplify the binop by seeing whether evaluating it on the incoming
477/// phi values yields the same result for every value. If so returns the common
478/// value, otherwise returns null.
480 Value *RHS, const SimplifyQuery &Q,
481 unsigned MaxRecurse) {
482 // Recursion is always used, so bail out at once if we already hit the limit.
483 if (!MaxRecurse--)
484 return nullptr;
485
486 PHINode *PI;
487 if (isa<PHINode>(LHS)) {
488 PI = cast<PHINode>(LHS);
489 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
490 if (!valueDominatesPHI(RHS, PI, Q.DT))
491 return nullptr;
492 } else {
493 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
494 PI = cast<PHINode>(RHS);
495 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
496 if (!valueDominatesPHI(LHS, PI, Q.DT))
497 return nullptr;
498 }
499
500 // Evaluate the BinOp on the incoming phi values.
501 Value *CommonValue = nullptr;
502 for (Use &Incoming : PI->incoming_values()) {
503 // If the incoming value is the phi node itself, it can safely be skipped.
504 if (Incoming == PI)
505 continue;
506 Instruction *InTI = PI->getIncomingBlock(Incoming)->getTerminator();
507 Value *V = PI == LHS
508 ? simplifyBinOp(Opcode, Incoming, RHS,
509 Q.getWithInstruction(InTI), MaxRecurse)
510 : simplifyBinOp(Opcode, LHS, Incoming,
511 Q.getWithInstruction(InTI), 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;
517 }
518
519 return CommonValue;
520}
521
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.
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;
531
532 // Make sure the phi is on the LHS.
533 if (!isa<PHINode>(LHS)) {
534 std::swap(LHS, RHS);
536 }
537 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
539
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;
543
544 // Evaluate the BinOp on the incoming phi values.
545 Value *CommonValue = nullptr;
546 for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
547 Value *Incoming = PI->getIncomingValue(u);
549 // If the incoming value is the phi node itself, it can safely be skipped.
550 if (Incoming == PI)
551 continue;
552 // Change the context instruction to the "edge" that flows into the phi.
553 // This is important because that is where incoming is actually "evaluated"
554 // even though it is used later somewhere else.
555 Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
556 MaxRecurse);
557 // If the operation failed to simplify, or simplified to a different value
558 // to previously, then give up.
559 if (!V || (CommonValue && V != CommonValue))
560 return nullptr;
561 CommonValue = V;
562 }
563
564 return CommonValue;
565}
566
568 Value *&Op0, Value *&Op1,
569 const SimplifyQuery &Q) {
570 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
571 if (auto *CRHS = dyn_cast<Constant>(Op1)) {
572 switch (Opcode) {
573 default:
574 break;
575 case Instruction::FAdd:
576 case Instruction::FSub:
577 case Instruction::FMul:
578 case Instruction::FDiv:
579 case Instruction::FRem:
580 if (Q.CtxI != nullptr)
581 return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CtxI);
582 }
583 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
584 }
585
586 // Canonicalize the constant to the RHS if this is a commutative operation.
587 if (Instruction::isCommutative(Opcode))
588 std::swap(Op0, Op1);
589 }
590 return nullptr;
591}
592
593/// Given operands for an Add, see if we can fold the result.
594/// If not, this returns null.
595static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
596 const SimplifyQuery &Q, unsigned MaxRecurse) {
597 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
598 return C;
599
600 // X + poison -> poison
601 if (isa<PoisonValue>(Op1))
602 return Op1;
603
604 // X + undef -> undef
605 if (Q.isUndefValue(Op1))
606 return Op1;
607
608 // X + 0 -> X
609 if (match(Op1, m_Zero()))
610 return Op0;
611
612 // If two operands are negative, return 0.
613 if (isKnownNegation(Op0, Op1))
614 return Constant::getNullValue(Op0->getType());
615
616 // X + (Y - X) -> Y
617 // (Y - X) + X -> Y
618 // Eg: X + -X -> 0
619 Value *Y = nullptr;
620 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
621 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
622 return Y;
623
624 // X + ~X -> -1 since ~X = -X-1
625 Type *Ty = Op0->getType();
626 if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
627 return Constant::getAllOnesValue(Ty);
628
629 // add nsw/nuw (xor Y, signmask), signmask --> Y
630 // The no-wrapping add guarantees that the top bit will be set by the add.
631 // Therefore, the xor must be clearing the already set sign bit of Y.
632 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
633 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
634 return Y;
635
636 // add nuw %x, -1 -> -1, because %x can only be 0.
637 if (IsNUW && match(Op1, m_AllOnes()))
638 return Op1; // Which is -1.
639
640 /// i1 add -> xor.
641 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
642 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
643 return V;
644
645 // Try some generic simplifications for associative operations.
646 if (Value *V =
647 simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
648 return V;
649
650 // Threading Add over selects and phi nodes is pointless, so don't bother.
651 // Threading over the select in "A + select(cond, B, C)" means evaluating
652 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
653 // only if B and C are equal. If B and C are equal then (since we assume
654 // that operands have already been simplified) "select(cond, B, C)" should
655 // have been simplified to the common value of B and C already. Analysing
656 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
657 // for threading over phi nodes.
658
659 return nullptr;
660}
661
662Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
663 const SimplifyQuery &Query) {
664 return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
665}
666
667/// Compute the base pointer and cumulative constant offsets for V.
668///
669/// This strips all constant offsets off of V, leaving it the base pointer, and
670/// accumulates the total constant offset applied in the returned constant.
671/// It returns zero if there are no constant offsets applied.
672///
673/// This is very similar to stripAndAccumulateConstantOffsets(), except it
674/// normalizes the offset bitwidth to the stripped pointer type, not the
675/// original pointer type.
677 assert(V->getType()->isPtrOrPtrVectorTy());
678
679 APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
680 V = V->stripAndAccumulateConstantOffsets(DL, Offset,
681 /*AllowNonInbounds=*/true);
682 // As that strip may trace through `addrspacecast`, need to sext or trunc
683 // the offset calculated.
684 return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
685}
686
687/// Compute the constant difference between two pointer values.
688/// If the difference is not a constant, returns zero.
690 Value *RHS) {
693
694 // If LHS and RHS are not related via constant offsets to the same base
695 // value, there is nothing we can do here.
696 if (LHS != RHS)
697 return nullptr;
698
699 // Otherwise, the difference of LHS - RHS can be computed as:
700 // LHS - RHS
701 // = (LHSOffset + Base) - (RHSOffset + Base)
702 // = LHSOffset - RHSOffset
703 Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
704 if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
705 Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
706 return Res;
707}
708
709/// Test if there is a dominating equivalence condition for the
710/// two operands. If there is, try to reduce the binary operation
711/// between the two operands.
712/// Example: Op0 - Op1 --> 0 when Op0 == Op1
713static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
714 const SimplifyQuery &Q, unsigned MaxRecurse) {
715 // Recursive run it can not get any benefit
716 if (MaxRecurse != RecursionLimit)
717 return nullptr;
718
719 std::optional<bool> Imp =
721 if (Imp && *Imp) {
722 Type *Ty = Op0->getType();
723 switch (Opcode) {
724 case Instruction::Sub:
725 case Instruction::Xor:
726 case Instruction::URem:
727 case Instruction::SRem:
728 return Constant::getNullValue(Ty);
729
730 case Instruction::SDiv:
731 case Instruction::UDiv:
732 return ConstantInt::get(Ty, 1);
733
734 case Instruction::And:
735 case Instruction::Or:
736 // Could be either one - choose Op1 since that's more likely a constant.
737 return Op1;
738 default:
739 break;
740 }
741 }
742 return nullptr;
743}
744
745/// Given operands for a Sub, see if we can fold the result.
746/// If not, this returns null.
747static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
748 const SimplifyQuery &Q, unsigned MaxRecurse) {
749 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
750 return C;
751
752 // X - poison -> poison
753 // poison - X -> poison
754 if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
755 return PoisonValue::get(Op0->getType());
756
757 // X - undef -> undef
758 // undef - X -> undef
759 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
760 return UndefValue::get(Op0->getType());
761
762 // X - 0 -> X
763 if (match(Op1, m_Zero()))
764 return Op0;
765
766 // X - X -> 0
767 if (Op0 == Op1)
768 return Constant::getNullValue(Op0->getType());
769
770 // Is this a negation?
771 if (match(Op0, m_Zero())) {
772 // 0 - X -> 0 if the sub is NUW.
773 if (IsNUW)
774 return Constant::getNullValue(Op0->getType());
775
777 if (Known.Zero.isMaxSignedValue()) {
778 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
779 // Op1 must be 0 because negating the minimum signed value is undefined.
780 if (IsNSW)
781 return Constant::getNullValue(Op0->getType());
782
783 // 0 - X -> X if X is 0 or the minimum signed value.
784 return Op1;
785 }
786 }
787
788 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
789 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
790 Value *X = nullptr, *Y = nullptr, *Z = Op1;
791 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
792 // See if "V === Y - Z" simplifies.
793 if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
794 // It does! Now see if "X + V" simplifies.
795 if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
796 // It does, we successfully reassociated!
797 ++NumReassoc;
798 return W;
799 }
800 // See if "V === X - Z" simplifies.
801 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
802 // It does! Now see if "Y + V" simplifies.
803 if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
804 // It does, we successfully reassociated!
805 ++NumReassoc;
806 return W;
807 }
808 }
809
810 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
811 // For example, X - (X + 1) -> -1
812 X = Op0;
813 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
814 // See if "V === X - Y" simplifies.
815 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
816 // It does! Now see if "V - Z" simplifies.
817 if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
818 // It does, we successfully reassociated!
819 ++NumReassoc;
820 return W;
821 }
822 // See if "V === X - Z" simplifies.
823 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
824 // It does! Now see if "V - Y" simplifies.
825 if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
826 // It does, we successfully reassociated!
827 ++NumReassoc;
828 return W;
829 }
830 }
831
832 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
833 // For example, X - (X - Y) -> Y.
834 Z = Op0;
835 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
836 // See if "V === Z - X" simplifies.
837 if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
838 // It does! Now see if "V + Y" simplifies.
839 if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
840 // It does, we successfully reassociated!
841 ++NumReassoc;
842 return W;
843 }
844
845 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
846 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
847 match(Op1, m_Trunc(m_Value(Y))))
848 if (X->getType() == Y->getType())
849 // See if "V === X - Y" simplifies.
850 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
851 // It does! Now see if "trunc V" simplifies.
852 if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
853 Q, MaxRecurse - 1))
854 // It does, return the simplified "trunc V".
855 return W;
856
857 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
858 if (match(Op0, m_PtrToIntOrAddr(m_Value(X))) &&
860 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
861 return ConstantFoldIntegerCast(Result, Op0->getType(), /*IsSigned*/ true,
862 Q.DL);
863 }
864
865 // i1 sub -> xor.
866 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
867 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
868 return V;
869
870 // Threading Sub over selects and phi nodes is pointless, so don't bother.
871 // Threading over the select in "A - select(cond, B, C)" means evaluating
872 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
873 // only if B and C are equal. If B and C are equal then (since we assume
874 // that operands have already been simplified) "select(cond, B, C)" should
875 // have been simplified to the common value of B and C already. Analysing
876 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
877 // for threading over phi nodes.
878
879 if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
880 return V;
881
882 // (sub nuw C_Mask, (xor X, C_Mask)) -> X
883 if (IsNUW) {
884 Value *X;
885 if (match(Op1, m_Xor(m_Value(X), m_Specific(Op0))) &&
886 match(Op0, m_LowBitMask()))
887 return X;
888 }
889
890 return nullptr;
891}
892
893Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
894 const SimplifyQuery &Q) {
895 return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
896}
897
898/// Given operands for a Mul, see if we can fold the result.
899/// If not, this returns null.
900static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
901 const SimplifyQuery &Q, unsigned MaxRecurse) {
902 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
903 return C;
904
905 // X * poison -> poison
906 if (isa<PoisonValue>(Op1))
907 return Op1;
908
909 // X * undef -> 0
910 // X * 0 -> 0
911 if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
912 return Constant::getNullValue(Op0->getType());
913
914 // X * 1 -> X
915 if (match(Op1, m_One()))
916 return Op0;
917
918 // (X / Y) * Y -> X if the division is exact.
919 Value *X = nullptr;
920 if (Q.IIQ.UseInstrInfo &&
921 (match(Op0,
922 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
923 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
924 return X;
925
926 if (Op0->getType()->isIntOrIntVectorTy(1)) {
927 // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
928 // representable). All other cases reduce to 0, so just return 0.
929 if (IsNSW)
930 return ConstantInt::getNullValue(Op0->getType());
931
932 // Treat "mul i1" as "and i1".
933 if (MaxRecurse)
934 if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
935 return V;
936 }
937
938 // Try some generic simplifications for associative operations.
939 if (Value *V =
940 simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
941 return V;
942
943 // Mul distributes over Add. Try some generic simplifications based on this.
944 if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
945 Instruction::Add, Q, MaxRecurse))
946 return V;
947
948 // If the operation is with the result of a select instruction, check whether
949 // operating on either branch of the select always yields the same value.
950 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
951 if (Value *V =
952 threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
953 return V;
954
955 // If the operation is with the result of a phi instruction, check whether
956 // operating on all incoming values of the phi always yields the same value.
957 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
958 if (Value *V =
959 threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
960 return V;
961
962 return nullptr;
963}
964
965Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
966 const SimplifyQuery &Q) {
967 return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
968}
969
970/// Given a predicate and two operands, return true if the comparison is true.
971/// This is a helper for div/rem simplification where we return some other value
972/// when we can prove a relationship between the operands.
974 const SimplifyQuery &Q, unsigned MaxRecurse) {
975 Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
977 return (C && C->isAllOnesValue());
978}
979
980/// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
981/// to simplify X % Y to X.
982static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
983 unsigned MaxRecurse, bool IsSigned) {
984 // Recursion is always used, so bail out at once if we already hit the limit.
985 if (!MaxRecurse--)
986 return false;
987
988 if (IsSigned) {
989 // (X srem Y) sdiv Y --> 0
990 if (match(X, m_SRem(m_Value(), m_Specific(Y))))
991 return true;
992
993 // |X| / |Y| --> 0
994 //
995 // We require that 1 operand is a simple constant. That could be extended to
996 // 2 variables if we computed the sign bit for each.
997 //
998 // Make sure that a constant is not the minimum signed value because taking
999 // the abs() of that is undefined.
1000 Type *Ty = X->getType();
1001 const APInt *C;
1002 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1003 // Is the variable divisor magnitude always greater than the constant
1004 // dividend magnitude?
1005 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1006 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1007 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1008 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1009 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1010 return true;
1011 }
1012 if (match(Y, m_APInt(C))) {
1013 // Special-case: we can't take the abs() of a minimum signed value. If
1014 // that's the divisor, then all we have to do is prove that the dividend
1015 // is also not the minimum signed value.
1016 if (C->isMinSignedValue())
1017 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1018
1019 // Is the variable dividend magnitude always less than the constant
1020 // divisor magnitude?
1021 // |X| < |C| --> X > -abs(C) and X < abs(C)
1022 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1023 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1024 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1025 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1026 return true;
1027 }
1028 return false;
1029 }
1030
1031 // IsSigned == false.
1032
1033 // Is the unsigned dividend known to be less than a constant divisor?
1034 // TODO: Convert this (and above) to range analysis
1035 // ("computeConstantRangeIncludingKnownBits")?
1036 const APInt *C;
1037 if (match(Y, m_APInt(C)) && computeKnownBits(X, Q).getMaxValue().ult(*C))
1038 return true;
1039
1040 // Try again for any divisor:
1041 // Is the dividend unsigned less than the divisor?
1042 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1043}
1044
1045/// Check for common or similar folds of integer division or integer remainder.
1046/// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
1048 Value *Op1, const SimplifyQuery &Q,
1049 unsigned MaxRecurse) {
1050 bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
1051 bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
1052
1053 Type *Ty = Op0->getType();
1054
1055 // X / undef -> poison
1056 // X % undef -> poison
1057 if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
1058 return PoisonValue::get(Ty);
1059
1060 // X / 0 -> poison
1061 // X % 0 -> poison
1062 // We don't need to preserve faults!
1063 if (match(Op1, m_Zero()))
1064 return PoisonValue::get(Ty);
1065
1066 // poison / X -> poison
1067 // poison % X -> poison
1068 if (isa<PoisonValue>(Op0))
1069 return Op0;
1070
1071 // undef / X -> 0
1072 // undef % X -> 0
1073 if (Q.isUndefValue(Op0))
1074 return Constant::getNullValue(Ty);
1075
1076 // 0 / X -> 0
1077 // 0 % X -> 0
1078 if (match(Op0, m_Zero()))
1079 return Constant::getNullValue(Op0->getType());
1080
1081 // X / X -> 1
1082 // X % X -> 0
1083 if (Op0 == Op1)
1084 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1085
1087 // X / 0 -> poison
1088 // X % 0 -> poison
1089 // If the divisor is known to be zero, just return poison. This can happen in
1090 // some cases where its provable indirectly the denominator is zero but it's
1091 // not trivially simplifiable (i.e known zero through a phi node).
1092 if (Known.isZero())
1093 return PoisonValue::get(Ty);
1094
1095 // X / 1 -> X
1096 // X % 1 -> 0
1097 // If the divisor can only be zero or one, we can't have division-by-zero
1098 // or remainder-by-zero, so assume the divisor is 1.
1099 // e.g. 1, zext (i8 X), sdiv X (Y and 1)
1100 if (Known.countMinLeadingZeros() == Known.getBitWidth() - 1)
1101 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1102
1103 // If X * Y does not overflow, then:
1104 // X * Y / Y -> X
1105 // X * Y % Y -> 0
1106 Value *X;
1107 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1109 // The multiplication can't overflow if it is defined not to, or if
1110 // X == A / Y for some A.
1111 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1112 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1113 (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1114 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1115 return IsDiv ? X : Constant::getNullValue(Op0->getType());
1116 }
1117 }
1118
1119 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1120 return IsDiv ? Constant::getNullValue(Op0->getType()) : Op0;
1121
1122 if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1123 return V;
1124
1125 // If the operation is with the result of a select instruction, check whether
1126 // operating on either branch of the select always yields the same value.
1127 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1128 if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1129 return V;
1130
1131 // If the operation is with the result of a phi instruction, check whether
1132 // operating on all incoming values of the phi always yields the same value.
1133 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1134 if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1135 return V;
1136
1137 return nullptr;
1138}
1139
1140/// These are simplifications common to SDiv and UDiv.
1142 bool IsExact, const SimplifyQuery &Q,
1143 unsigned MaxRecurse) {
1144 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1145 return C;
1146
1147 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1148 return V;
1149
1150 const APInt *DivC;
1151 if (IsExact && match(Op1, m_APInt(DivC))) {
1152 // If this is an exact divide by a constant, then the dividend (Op0) must
1153 // have at least as many trailing zeros as the divisor to divide evenly. If
1154 // it has less trailing zeros, then the result must be poison.
1155 if (DivC->countr_zero()) {
1156 KnownBits KnownOp0 = computeKnownBits(Op0, Q);
1157 if (KnownOp0.countMaxTrailingZeros() < DivC->countr_zero())
1158 return PoisonValue::get(Op0->getType());
1159 }
1160
1161 // udiv exact (mul nsw X, C), C --> X
1162 // sdiv exact (mul nuw X, C), C --> X
1163 // where C is not a power of 2.
1164 Value *X;
1165 if (!DivC->isPowerOf2() &&
1166 (Opcode == Instruction::UDiv
1167 ? match(Op0, m_NSWMul(m_Value(X), m_Specific(Op1)))
1168 : match(Op0, m_NUWMul(m_Value(X), m_Specific(Op1)))))
1169 return X;
1170 }
1171
1172 return nullptr;
1173}
1174
1175/// These are simplifications common to SRem and URem.
1177 const SimplifyQuery &Q, unsigned MaxRecurse) {
1178 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1179 return C;
1180
1181 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1182 return V;
1183
1184 // (X << Y) % X -> 0
1185 if (Q.IIQ.UseInstrInfo) {
1186 if ((Opcode == Instruction::SRem &&
1187 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1188 (Opcode == Instruction::URem &&
1189 match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))
1190 return Constant::getNullValue(Op0->getType());
1191
1192 const APInt *C0;
1193 if (match(Op1, m_APInt(C0))) {
1194 // (srem (mul nsw X, C1), C0) -> 0 if C1 s% C0 == 0
1195 // (urem (mul nuw X, C1), C0) -> 0 if C1 u% C0 == 0
1196 if (Opcode == Instruction::SRem
1197 ? match(Op0,
1198 m_NSWMul(m_Value(), m_CheckedInt([C0](const APInt &C) {
1199 return C.srem(*C0).isZero();
1200 })))
1201 : match(Op0,
1202 m_NUWMul(m_Value(), m_CheckedInt([C0](const APInt &C) {
1203 return C.urem(*C0).isZero();
1204 }))))
1205 return Constant::getNullValue(Op0->getType());
1206 }
1207 }
1208 return nullptr;
1209}
1210
1211/// Given operands for an SDiv, see if we can fold the result.
1212/// If not, this returns null.
1213static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1214 const SimplifyQuery &Q, unsigned MaxRecurse) {
1215 // If two operands are negated and no signed overflow, return -1.
1216 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1217 return Constant::getAllOnesValue(Op0->getType());
1218
1219 return simplifyDiv(Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1220}
1221
1222Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1223 const SimplifyQuery &Q) {
1224 return ::simplifySDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1225}
1226
1227/// Given operands for a UDiv, see if we can fold the result.
1228/// If not, this returns null.
1229static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1230 const SimplifyQuery &Q, unsigned MaxRecurse) {
1231 return simplifyDiv(Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1232}
1233
1234Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1235 const SimplifyQuery &Q) {
1236 return ::simplifyUDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1237}
1238
1239/// Given operands for an SRem, see if we can fold the result.
1240/// If not, this returns null.
1241static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1242 unsigned MaxRecurse) {
1243 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1244 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1245 Value *X;
1246 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1247 return ConstantInt::getNullValue(Op0->getType());
1248
1249 // If the two operands are negated, return 0.
1250 if (isKnownNegation(Op0, Op1))
1251 return ConstantInt::getNullValue(Op0->getType());
1252
1253 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1254}
1255
1257 return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
1258}
1259
1260/// Given operands for a URem, see if we can fold the result.
1261/// If not, this returns null.
1262static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1263 unsigned MaxRecurse) {
1264 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1265}
1266
1268 return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
1269}
1270
1271/// Returns true if a shift by \c Amount always yields poison.
1272static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1273 Constant *C = dyn_cast<Constant>(Amount);
1274 if (!C)
1275 return false;
1276
1277 // X shift by undef -> poison because it may shift by the bitwidth.
1278 if (Q.isUndefValue(C))
1279 return true;
1280
1281 // Shifting by the bitwidth or more is poison. This covers scalars and
1282 // fixed/scalable vectors with splat constants.
1283 const APInt *AmountC;
1284 if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
1285 return true;
1286
1287 // Try harder for fixed-length vectors:
1288 // If all lanes of a vector shift are poison, the whole shift is poison.
1290 for (unsigned I = 0,
1291 E = cast<FixedVectorType>(C->getType())->getNumElements();
1292 I != E; ++I)
1293 if (!isPoisonShift(C->getAggregateElement(I), Q))
1294 return false;
1295 return true;
1296 }
1297
1298 return false;
1299}
1300
1301/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1302/// If not, this returns null.
1304 Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1305 unsigned MaxRecurse) {
1306 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1307 return C;
1308
1309 // poison shift by X -> poison
1310 if (isa<PoisonValue>(Op0))
1311 return Op0;
1312
1313 // 0 shift by X -> 0
1314 if (match(Op0, m_Zero()))
1315 return Constant::getNullValue(Op0->getType());
1316
1317 // X shift by 0 -> X
1318 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1319 // would be poison.
1320 Value *X;
1321 if (match(Op1, m_Zero()) ||
1322 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1323 return Op0;
1324
1325 // Fold undefined shifts.
1326 if (isPoisonShift(Op1, Q))
1327 return PoisonValue::get(Op0->getType());
1328
1329 // If the operation is with the result of a select instruction, check whether
1330 // operating on either branch of the select always yields the same value.
1331 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1332 if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1333 return V;
1334
1335 // If the operation is with the result of a phi instruction, check whether
1336 // operating on all incoming values of the phi always yields the same value.
1337 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1338 if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1339 return V;
1340
1341 // If any bits in the shift amount make that value greater than or equal to
1342 // the number of bits in the type, the shift is undefined.
1343 KnownBits KnownAmt = computeKnownBits(Op1, Q);
1344 if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1345 return PoisonValue::get(Op0->getType());
1346
1347 // If all valid bits in the shift amount are known zero, the first operand is
1348 // unchanged.
1349 unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1350 if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1351 return Op0;
1352
1353 // Check for nsw shl leading to a poison value.
1354 if (IsNSW) {
1355 assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1356 KnownBits KnownVal = computeKnownBits(Op0, Q);
1357 KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1358
1359 if (KnownVal.Zero.isSignBitSet())
1360 KnownShl.Zero.setSignBit();
1361 if (KnownVal.One.isSignBitSet())
1362 KnownShl.One.setSignBit();
1363
1364 if (KnownShl.hasConflict())
1365 return PoisonValue::get(Op0->getType());
1366 }
1367
1368 return nullptr;
1369}
1370
1371/// Given operands for an LShr or AShr, see if we can fold the result. If not,
1372/// this returns null.
1374 Value *Op1, bool IsExact,
1375 const SimplifyQuery &Q, unsigned MaxRecurse) {
1376 if (Value *V =
1377 simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1378 return V;
1379
1380 // X >> X -> 0
1381 if (Op0 == Op1)
1382 return Constant::getNullValue(Op0->getType());
1383
1384 // undef >> X -> 0
1385 // undef >> X -> undef (if it's exact)
1386 if (Q.isUndefValue(Op0))
1387 return IsExact ? Op0 : Constant::getNullValue(Op0->getType());
1388
1389 // The low bit cannot be shifted out of an exact shift if it is set.
1390 // TODO: Generalize by counting trailing zeros (see fold for exact division).
1391 if (IsExact) {
1392 KnownBits Op0Known = computeKnownBits(Op0, Q);
1393 if (Op0Known.One[0])
1394 return Op0;
1395 }
1396
1397 return nullptr;
1398}
1399
1400/// Given operands for an Shl, see if we can fold the result.
1401/// If not, this returns null.
1402static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1403 const SimplifyQuery &Q, unsigned MaxRecurse) {
1404 if (Value *V =
1405 simplifyShift(Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
1406 return V;
1407
1408 Type *Ty = Op0->getType();
1409 // undef << X -> 0
1410 // undef << X -> undef if (if it's NSW/NUW)
1411 if (Q.isUndefValue(Op0))
1412 return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Ty);
1413
1414 // (X >> A) << A -> X
1415 Value *X;
1416 if (Q.IIQ.UseInstrInfo &&
1417 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1418 return X;
1419
1420 // shl nuw i8 C, %x -> C iff C has sign bit set.
1421 if (IsNUW && match(Op0, m_Negative()))
1422 return Op0;
1423 // NOTE: could use computeKnownBits() / LazyValueInfo,
1424 // but the cost-benefit analysis suggests it isn't worth it.
1425
1426 // "nuw" guarantees that only zeros are shifted out, and "nsw" guarantees
1427 // that the sign-bit does not change, so the only input that does not
1428 // produce poison is 0, and "0 << (bitwidth-1) --> 0".
1429 if (IsNSW && IsNUW &&
1430 match(Op1, m_SpecificInt(Ty->getScalarSizeInBits() - 1)))
1431 return Constant::getNullValue(Ty);
1432
1433 return nullptr;
1434}
1435
1436Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1437 const SimplifyQuery &Q) {
1438 return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
1439}
1440
1441/// Given operands for an LShr, see if we can fold the result.
1442/// If not, this returns null.
1443static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1444 const SimplifyQuery &Q, unsigned MaxRecurse) {
1445 if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, IsExact, Q,
1446 MaxRecurse))
1447 return V;
1448
1449 // (X << A) >> A -> X
1450 Value *X;
1451 if (Q.IIQ.UseInstrInfo && match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1452 return X;
1453
1454 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1455 // We can return X as we do in the above case since OR alters no bits in X.
1456 // SimplifyDemandedBits in InstCombine can do more general optimization for
1457 // bit manipulation. This pattern aims to provide opportunities for other
1458 // optimizers by supporting a simple but common case in InstSimplify.
1459 Value *Y;
1460 const APInt *ShRAmt, *ShLAmt;
1461 if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(ShRAmt)) &&
1462 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1463 *ShRAmt == *ShLAmt) {
1464 const KnownBits YKnown = computeKnownBits(Y, Q);
1465 const unsigned EffWidthY = YKnown.countMaxActiveBits();
1466 if (ShRAmt->uge(EffWidthY))
1467 return X;
1468 }
1469
1470 return nullptr;
1471}
1472
1473Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1474 const SimplifyQuery &Q) {
1475 return ::simplifyLShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1476}
1477
1478/// Given operands for an AShr, see if we can fold the result.
1479/// If not, this returns null.
1480static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1481 const SimplifyQuery &Q, unsigned MaxRecurse) {
1482 if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, IsExact, Q,
1483 MaxRecurse))
1484 return V;
1485
1486 // -1 >>a X --> -1
1487 // (-1 << X) a>> X --> -1
1488 // We could return the original -1 constant to preserve poison elements.
1489 if (match(Op0, m_AllOnes()) ||
1490 match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1491 return Constant::getAllOnesValue(Op0->getType());
1492
1493 // (X << A) >> A -> X
1494 Value *X;
1495 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1496 return X;
1497
1498 // Arithmetic shifting an all-sign-bit value is a no-op.
1499 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, Q.AC, Q.CtxI, Q.DT);
1500 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1501 return Op0;
1502
1503 return nullptr;
1504}
1505
1506Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1507 const SimplifyQuery &Q) {
1508 return ::simplifyAShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1509}
1510
1511/// Commuted variants are assumed to be handled by calling this function again
1512/// with the parameters swapped.
1514 ICmpInst *UnsignedICmp, bool IsAnd,
1515 const SimplifyQuery &Q) {
1516 Value *X, *Y;
1517
1518 CmpPredicate EqPred;
1519 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1520 !ICmpInst::isEquality(EqPred))
1521 return nullptr;
1522
1523 CmpPredicate UnsignedPred;
1524
1525 Value *A, *B;
1526 // Y = (A - B);
1527 if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1528 if (match(UnsignedICmp,
1529 m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1530 ICmpInst::isUnsigned(UnsignedPred)) {
1531 // A >=/<= B || (A - B) != 0 <--> true
1532 if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1533 UnsignedPred == ICmpInst::ICMP_ULE) &&
1534 EqPred == ICmpInst::ICMP_NE && !IsAnd)
1535 return ConstantInt::getTrue(UnsignedICmp->getType());
1536 // A </> B && (A - B) == 0 <--> false
1537 if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1538 UnsignedPred == ICmpInst::ICMP_UGT) &&
1539 EqPred == ICmpInst::ICMP_EQ && IsAnd)
1540 return ConstantInt::getFalse(UnsignedICmp->getType());
1541
1542 // A </> B && (A - B) != 0 <--> A </> B
1543 // A </> B || (A - B) != 0 <--> (A - B) != 0
1544 if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1545 UnsignedPred == ICmpInst::ICMP_UGT))
1546 return IsAnd ? UnsignedICmp : ZeroICmp;
1547
1548 // A <=/>= B && (A - B) == 0 <--> (A - B) == 0
1549 // A <=/>= B || (A - B) == 0 <--> A <=/>= B
1550 if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1551 UnsignedPred == ICmpInst::ICMP_UGE))
1552 return IsAnd ? ZeroICmp : UnsignedICmp;
1553 }
1554
1555 // Given Y = (A - B)
1556 // Y >= A && Y != 0 --> Y >= A iff B != 0
1557 // Y < A || Y == 0 --> Y < A iff B != 0
1558 if (match(UnsignedICmp,
1559 m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1560 if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1561 EqPred == ICmpInst::ICMP_NE && isKnownNonZero(B, Q))
1562 return UnsignedICmp;
1563 if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1564 EqPred == ICmpInst::ICMP_EQ && isKnownNonZero(B, Q))
1565 return UnsignedICmp;
1566 }
1567 }
1568
1569 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1570 ICmpInst::isUnsigned(UnsignedPred))
1571 ;
1572 else if (match(UnsignedICmp,
1573 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1574 ICmpInst::isUnsigned(UnsignedPred))
1575 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1576 else
1577 return nullptr;
1578
1579 // X > Y && Y == 0 --> Y == 0 iff X != 0
1580 // X > Y || Y == 0 --> X > Y iff X != 0
1581 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1582 isKnownNonZero(X, Q))
1583 return IsAnd ? ZeroICmp : UnsignedICmp;
1584
1585 // X <= Y && Y != 0 --> X <= Y iff X != 0
1586 // X <= Y || Y != 0 --> Y != 0 iff X != 0
1587 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1588 isKnownNonZero(X, Q))
1589 return IsAnd ? UnsignedICmp : ZeroICmp;
1590
1591 // The transforms below here are expected to be handled more generally with
1592 // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1593 // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1594 // these are candidates for removal.
1595
1596 // X < Y && Y != 0 --> X < Y
1597 // X < Y || Y != 0 --> Y != 0
1598 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1599 return IsAnd ? UnsignedICmp : ZeroICmp;
1600
1601 // X >= Y && Y == 0 --> Y == 0
1602 // X >= Y || Y == 0 --> X >= Y
1603 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1604 return IsAnd ? ZeroICmp : UnsignedICmp;
1605
1606 // X < Y && Y == 0 --> false
1607 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1608 IsAnd)
1609 return getFalse(UnsignedICmp->getType());
1610
1611 // X >= Y || Y != 0 --> true
1612 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1613 !IsAnd)
1614 return getTrue(UnsignedICmp->getType());
1615
1616 return nullptr;
1617}
1618
1619/// Test if a pair of compares with a shared operand and 2 constants has an
1620/// empty set intersection, full set union, or if one compare is a superset of
1621/// the other.
1623 bool IsAnd) {
1624 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1625 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1626 return nullptr;
1627
1628 const APInt *C0, *C1;
1629 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1630 !match(Cmp1->getOperand(1), m_APInt(C1)))
1631 return nullptr;
1632
1633 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1634 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1635
1636 // For and-of-compares, check if the intersection is empty:
1637 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1638 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1639 return getFalse(Cmp0->getType());
1640
1641 // For or-of-compares, check if the union is full:
1642 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1643 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1644 return getTrue(Cmp0->getType());
1645
1646 // Is one range a superset of the other?
1647 // If this is and-of-compares, take the smaller set:
1648 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1649 // If this is or-of-compares, take the larger set:
1650 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1651 if (Range0.contains(Range1))
1652 return IsAnd ? Cmp1 : Cmp0;
1653 if (Range1.contains(Range0))
1654 return IsAnd ? Cmp0 : Cmp1;
1655
1656 return nullptr;
1657}
1658
1660 const InstrInfoQuery &IIQ) {
1661 // (icmp (add V, C0), C1) & (icmp V, C0)
1662 CmpPredicate Pred0, Pred1;
1663 const APInt *C0, *C1;
1664 Value *V;
1665 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1666 return nullptr;
1667
1668 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1669 return nullptr;
1670
1671 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1672 if (AddInst->getOperand(1) != Op1->getOperand(1))
1673 return nullptr;
1674
1675 Type *ITy = Op0->getType();
1676 bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1677 bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1678
1679 const APInt Delta = *C1 - *C0;
1680 if (C0->isStrictlyPositive()) {
1681 if (Delta == 2) {
1682 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1683 return getFalse(ITy);
1684 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1685 return getFalse(ITy);
1686 }
1687 if (Delta == 1) {
1688 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1689 return getFalse(ITy);
1690 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1691 return getFalse(ITy);
1692 }
1693 }
1694 if (C0->getBoolValue() && IsNUW) {
1695 if (Delta == 2)
1696 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1697 return getFalse(ITy);
1698 if (Delta == 1)
1699 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1700 return getFalse(ITy);
1701 }
1702
1703 return nullptr;
1704}
1705
1707 const SimplifyQuery &Q) {
1708 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1709 return X;
1710 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1711 return X;
1712
1713 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1714 return X;
1715
1716 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1717 return X;
1718 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1719 return X;
1720
1721 return nullptr;
1722}
1723
1725 const InstrInfoQuery &IIQ) {
1726 // (icmp (add V, C0), C1) | (icmp V, C0)
1727 CmpPredicate Pred0, Pred1;
1728 const APInt *C0, *C1;
1729 Value *V;
1730 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1731 return nullptr;
1732
1733 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1734 return nullptr;
1735
1736 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1737 if (AddInst->getOperand(1) != Op1->getOperand(1))
1738 return nullptr;
1739
1740 Type *ITy = Op0->getType();
1741 bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1742 bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1743
1744 const APInt Delta = *C1 - *C0;
1745 if (C0->isStrictlyPositive()) {
1746 if (Delta == 2) {
1747 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1748 return getTrue(ITy);
1749 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1750 return getTrue(ITy);
1751 }
1752 if (Delta == 1) {
1753 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1754 return getTrue(ITy);
1755 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1756 return getTrue(ITy);
1757 }
1758 }
1759 if (C0->getBoolValue() && IsNUW) {
1760 if (Delta == 2)
1761 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1762 return getTrue(ITy);
1763 if (Delta == 1)
1764 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1765 return getTrue(ITy);
1766 }
1767
1768 return nullptr;
1769}
1770
1772 const SimplifyQuery &Q) {
1773 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1774 return X;
1775 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1776 return X;
1777
1778 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1779 return X;
1780
1781 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1782 return X;
1783 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1784 return X;
1785
1786 return nullptr;
1787}
1788
1789/// Test if a pair of compares with a shared operand and 2 constants has an
1790/// empty set intersection, full set union, or if one compare is a superset of
1791/// the other.
1793 bool IsAnd) {
1794 // Look for this pattern: {and/or} (fcmp X, C0), (fcmp X, C1)).
1795 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1796 return nullptr;
1797
1798 const APFloat *C0, *C1;
1799 if (!match(Cmp0->getOperand(1), m_APFloat(C0)) ||
1800 !match(Cmp1->getOperand(1), m_APFloat(C1)))
1801 return nullptr;
1802
1804 IsAnd ? Cmp0->getPredicate() : Cmp0->getInversePredicate(), *C0);
1806 IsAnd ? Cmp1->getPredicate() : Cmp1->getInversePredicate(), *C1);
1807
1808 if (!Range0 || !Range1)
1809 return nullptr;
1810
1811 // For and-of-compares, check if the intersection is empty:
1812 // (fcmp X, C0) && (fcmp X, C1) --> empty set --> false
1813 if (Range0->intersectWith(*Range1).isEmptySet())
1814 return ConstantInt::getBool(Cmp0->getType(), !IsAnd);
1815
1816 // Is one range a superset of the other?
1817 // If this is and-of-compares, take the smaller set:
1818 // (fcmp ogt X, 4) && (fcmp ogt X, 42) --> fcmp ogt X, 42
1819 // If this is or-of-compares, take the larger set:
1820 // (fcmp ogt X, 4) || (fcmp ogt X, 42) --> fcmp ogt X, 4
1821 if (Range0->contains(*Range1))
1822 return Cmp1;
1823 if (Range1->contains(*Range0))
1824 return Cmp0;
1825
1826 return nullptr;
1827}
1828
1830 FCmpInst *RHS, bool IsAnd) {
1831 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1832 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1833 if (LHS0->getType() != RHS0->getType())
1834 return nullptr;
1835
1836 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1837 auto AbsOrSelfLHS0 = m_CombineOr(m_Specific(LHS0), m_FAbs(m_Specific(LHS0)));
1838 if ((PredL == FCmpInst::FCMP_ORD || PredL == FCmpInst::FCMP_UNO) &&
1839 ((FCmpInst::isOrdered(PredR) && IsAnd) ||
1840 (FCmpInst::isUnordered(PredR) && !IsAnd))) {
1841 // (fcmp ord X, 0) & (fcmp o** X/abs(X), Y) --> fcmp o** X/abs(X), Y
1842 // (fcmp uno X, 0) & (fcmp o** X/abs(X), Y) --> false
1843 // (fcmp uno X, 0) | (fcmp u** X/abs(X), Y) --> fcmp u** X/abs(X), Y
1844 // (fcmp ord X, 0) | (fcmp u** X/abs(X), Y) --> true
1845 if ((match(RHS0, AbsOrSelfLHS0) || match(RHS1, AbsOrSelfLHS0)) &&
1846 match(LHS1, m_PosZeroFP()))
1847 return FCmpInst::isOrdered(PredL) == FCmpInst::isOrdered(PredR)
1848 ? static_cast<Value *>(RHS)
1849 : ConstantInt::getBool(LHS->getType(), !IsAnd);
1850 }
1851
1852 auto AbsOrSelfRHS0 = m_CombineOr(m_Specific(RHS0), m_FAbs(m_Specific(RHS0)));
1853 if ((PredR == FCmpInst::FCMP_ORD || PredR == FCmpInst::FCMP_UNO) &&
1854 ((FCmpInst::isOrdered(PredL) && IsAnd) ||
1855 (FCmpInst::isUnordered(PredL) && !IsAnd))) {
1856 // (fcmp o** X/abs(X), Y) & (fcmp ord X, 0) --> fcmp o** X/abs(X), Y
1857 // (fcmp o** X/abs(X), Y) & (fcmp uno X, 0) --> false
1858 // (fcmp u** X/abs(X), Y) | (fcmp uno X, 0) --> fcmp u** X/abs(X), Y
1859 // (fcmp u** X/abs(X), Y) | (fcmp ord X, 0) --> true
1860 if ((match(LHS0, AbsOrSelfRHS0) || match(LHS1, AbsOrSelfRHS0)) &&
1861 match(RHS1, m_PosZeroFP()))
1862 return FCmpInst::isOrdered(PredL) == FCmpInst::isOrdered(PredR)
1863 ? static_cast<Value *>(LHS)
1864 : ConstantInt::getBool(LHS->getType(), !IsAnd);
1865 }
1866
1867 if (auto *V = simplifyAndOrOfFCmpsWithConstants(LHS, RHS, IsAnd))
1868 return V;
1869
1870 return nullptr;
1871}
1872
1874 Value *Op1, bool IsAnd) {
1875 // Look through casts of the 'and' operands to find compares.
1876 auto *Cast0 = dyn_cast<CastInst>(Op0);
1877 auto *Cast1 = dyn_cast<CastInst>(Op1);
1878 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1879 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1880 Op0 = Cast0->getOperand(0);
1881 Op1 = Cast1->getOperand(0);
1882 }
1883
1884 Value *V = nullptr;
1885 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1886 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1887 if (ICmp0 && ICmp1)
1888 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1889 : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1890
1891 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1892 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1893 if (FCmp0 && FCmp1)
1894 V = simplifyAndOrOfFCmps(Q, FCmp0, FCmp1, IsAnd);
1895
1896 if (!V)
1897 return nullptr;
1898 if (!Cast0)
1899 return V;
1900
1901 // If we looked through casts, we can only handle a constant simplification
1902 // because we are not allowed to create a cast instruction here.
1903 if (auto *C = dyn_cast<Constant>(V))
1904 return ConstantFoldCastOperand(Cast0->getOpcode(), C, Cast0->getType(),
1905 Q.DL);
1906
1907 return nullptr;
1908}
1909
1910static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
1911 const SimplifyQuery &Q,
1912 bool AllowRefinement,
1914 unsigned MaxRecurse);
1915
1916static Value *simplifyAndOrWithICmpEq(unsigned Opcode, Value *Op0, Value *Op1,
1917 const SimplifyQuery &Q,
1918 unsigned MaxRecurse) {
1919 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1920 "Must be and/or");
1922 Value *A, *B;
1923 if (!match(Op0, m_ICmpLike(Pred, m_Value(A), m_Value(B))) ||
1925 return nullptr;
1926
1927 auto Simplify = [&](Value *Res) -> Value * {
1928 Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, Res->getType());
1929
1930 // and (icmp eq a, b), x implies (a==b) inside x.
1931 // or (icmp ne a, b), x implies (a==b) inside x.
1932 // If x simplifies to true/false, we can simplify the and/or.
1933 if (Pred ==
1934 (Opcode == Instruction::And ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
1935 if (Res == Absorber)
1936 return Absorber;
1937 if (Res == ConstantExpr::getBinOpIdentity(Opcode, Res->getType()))
1938 return Op0;
1939 return nullptr;
1940 }
1941
1942 // If we have and (icmp ne a, b), x and for a==b we can simplify x to false,
1943 // then we can drop the icmp, as x will already be false in the case where
1944 // the icmp is false. Similar for or and true.
1945 if (Res == Absorber)
1946 return Op1;
1947 return nullptr;
1948 };
1949
1950 // In the final case (Res == Absorber with inverted predicate), it is safe to
1951 // refine poison during simplification, but not undef. For simplicity always
1952 // disable undef-based folds here.
1953 if (Value *Res = simplifyWithOpReplaced(Op1, A, B, Q.getWithoutUndef(),
1954 /* AllowRefinement */ true,
1955 /* DropFlags */ nullptr, MaxRecurse))
1956 return Simplify(Res);
1957 if (Value *Res = simplifyWithOpReplaced(Op1, B, A, Q.getWithoutUndef(),
1958 /* AllowRefinement */ true,
1959 /* DropFlags */ nullptr, MaxRecurse))
1960 return Simplify(Res);
1961
1962 return nullptr;
1963}
1964
1965/// Given a bitwise logic op, check if the operands are add/sub with a common
1966/// source value and inverted constant (identity: C - X -> ~(X + ~C)).
1968 Instruction::BinaryOps Opcode) {
1969 assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
1970 assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
1971 Value *X;
1972 Constant *C1, *C2;
1973 if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
1974 match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
1975 (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
1976 match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
1977 if (ConstantExpr::getNot(C1) == C2) {
1978 // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
1979 // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
1980 // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
1981 Type *Ty = Op0->getType();
1982 return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
1984 }
1985 }
1986 return nullptr;
1987}
1988
1989// Commutative patterns for and that will be tried with both operand orders.
1991 const SimplifyQuery &Q,
1992 unsigned MaxRecurse) {
1993 // ~A & A = 0
1994 if (match(Op0, m_Not(m_Specific(Op1))))
1995 return Constant::getNullValue(Op0->getType());
1996
1997 // (A | ?) & A = A
1998 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1999 return Op1;
2000
2001 // (X | ~Y) & (X | Y) --> X
2002 Value *X, *Y;
2003 if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2004 match(Op1, m_c_Or(m_Specific(X), m_Specific(Y))))
2005 return X;
2006
2007 // If we have a multiplication overflow check that is being 'and'ed with a
2008 // check that one of the multipliers is not zero, we can omit the 'and', and
2009 // only keep the overflow check.
2010 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2011 return Op1;
2012
2013 // -A & A = A if A is a power of two or zero.
2014 if (match(Op0, m_Neg(m_Specific(Op1))) &&
2015 isKnownToBeAPowerOfTwo(Op1, /*OrZero=*/true, Q))
2016 return Op1;
2017
2018 // This is a similar pattern used for checking if a value is a power-of-2:
2019 // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2020 if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2021 isKnownToBeAPowerOfTwo(Op1, /*OrZero=*/true, Q))
2022 return Constant::getNullValue(Op1->getType());
2023
2024 // (x << N) & ((x << M) - 1) --> 0, where x is known to be a power of 2 and
2025 // M <= N.
2026 const APInt *Shift1, *Shift2;
2027 if (match(Op0, m_Shl(m_Value(X), m_APInt(Shift1))) &&
2028 match(Op1, m_Add(m_Shl(m_Specific(X), m_APInt(Shift2)), m_AllOnes())) &&
2029 isKnownToBeAPowerOfTwo(X, /*OrZero=*/true, Q) && Shift1->uge(*Shift2))
2030 return Constant::getNullValue(Op0->getType());
2031
2032 if (Value *V =
2033 simplifyAndOrWithICmpEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2034 return V;
2035
2036 return nullptr;
2037}
2038
2039/// Given operands for an And, see if we can fold the result.
2040/// If not, this returns null.
2041static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2042 unsigned MaxRecurse) {
2043 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2044 return C;
2045
2046 // X & poison -> poison
2047 if (isa<PoisonValue>(Op1))
2048 return Op1;
2049
2050 // X & undef -> 0
2051 if (Q.isUndefValue(Op1))
2052 return Constant::getNullValue(Op0->getType());
2053
2054 // X & X = X
2055 if (Op0 == Op1)
2056 return Op0;
2057
2058 // X & 0 = 0
2059 if (match(Op1, m_Zero()))
2060 return Constant::getNullValue(Op0->getType());
2061
2062 // X & -1 = X
2063 if (match(Op1, m_AllOnes()))
2064 return Op0;
2065
2066 if (Value *Res = simplifyAndCommutative(Op0, Op1, Q, MaxRecurse))
2067 return Res;
2068 if (Value *Res = simplifyAndCommutative(Op1, Op0, Q, MaxRecurse))
2069 return Res;
2070
2071 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2072 return V;
2073
2074 // A mask that only clears known zeros of a shifted value is a no-op.
2075 const APInt *Mask;
2076 const APInt *ShAmt;
2077 Value *X, *Y;
2078 if (match(Op1, m_APInt(Mask))) {
2079 // If all bits in the inverted and shifted mask are clear:
2080 // and (shl X, ShAmt), Mask --> shl X, ShAmt
2081 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2082 (~(*Mask)).lshr(*ShAmt).isZero())
2083 return Op0;
2084
2085 // If all bits in the inverted and shifted mask are clear:
2086 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2087 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2088 (~(*Mask)).shl(*ShAmt).isZero())
2089 return Op0;
2090 }
2091
2092 // and 2^x-1, 2^C --> 0 where x <= C.
2093 const APInt *PowerC;
2094 Value *Shift;
2095 if (match(Op1, m_Power2(PowerC)) &&
2096 match(Op0, m_Add(m_Value(Shift), m_AllOnes())) &&
2097 isKnownToBeAPowerOfTwo(Shift, /*OrZero=*/false, Q)) {
2098 KnownBits Known = computeKnownBits(Shift, Q);
2099 // Use getActiveBits() to make use of the additional power of two knowledge
2100 if (PowerC->getActiveBits() >= Known.getMaxValue().getActiveBits())
2101 return ConstantInt::getNullValue(Op1->getType());
2102 }
2103
2104 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2105 return V;
2106
2107 // zext(X) & sext(X) --> zext(X)
2108 // sext(X) & zext(X) --> zext(X)
2109 {
2110 Value *X = nullptr;
2111 if (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Specific(X))))
2112 return Op0;
2113 if (match(Op1, m_ZExt(m_Value(X))) && match(Op0, m_SExt(m_Specific(X))))
2114 return Op1;
2115 }
2116
2117 // Try some generic simplifications for associative operations.
2118 if (Value *V =
2119 simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
2120 return V;
2121
2122 // And distributes over Or. Try some generic simplifications based on this.
2123 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2124 Instruction::Or, Q, MaxRecurse))
2125 return V;
2126
2127 // And distributes over Xor. Try some generic simplifications based on this.
2128 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2129 Instruction::Xor, Q, MaxRecurse))
2130 return V;
2131
2132 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2133 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2134 // A & (A && B) -> A && B
2135 if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2136 return Op1;
2137 else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2138 return Op0;
2139 }
2140 // If the operation is with the result of a select instruction, check
2141 // whether operating on either branch of the select always yields the same
2142 // value.
2143 if (Value *V =
2144 threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
2145 return V;
2146 }
2147
2148 // If the operation is with the result of a phi instruction, check whether
2149 // operating on all incoming values of the phi always yields the same value.
2150 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2151 if (Value *V =
2152 threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
2153 return V;
2154
2155 // Assuming the effective width of Y is not larger than A, i.e. all bits
2156 // from X and Y are disjoint in (X << A) | Y,
2157 // if the mask of this AND op covers all bits of X or Y, while it covers
2158 // no bits from the other, we can bypass this AND op. E.g.,
2159 // ((X << A) | Y) & Mask -> Y,
2160 // if Mask = ((1 << effective_width_of(Y)) - 1)
2161 // ((X << A) | Y) & Mask -> X << A,
2162 // if Mask = ((1 << effective_width_of(X)) - 1) << A
2163 // SimplifyDemandedBits in InstCombine can optimize the general case.
2164 // This pattern aims to help other passes for a common case.
2165 Value *XShifted;
2166 if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(Mask)) &&
2168 m_Value(XShifted)),
2169 m_Value(Y)))) {
2170 const unsigned Width = Op0->getType()->getScalarSizeInBits();
2171 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2172 const KnownBits YKnown = computeKnownBits(Y, Q);
2173 const unsigned EffWidthY = YKnown.countMaxActiveBits();
2174 if (EffWidthY <= ShftCnt) {
2175 const KnownBits XKnown = computeKnownBits(X, Q);
2176 const unsigned EffWidthX = XKnown.countMaxActiveBits();
2177 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2178 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2179 // If the mask is extracting all bits from X or Y as is, we can skip
2180 // this AND op.
2181 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2182 return Y;
2183 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2184 return XShifted;
2185 }
2186 }
2187
2188 // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2189 // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2191 if (match(Op0, m_c_Xor(m_Value(X),
2193 m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2195 return Constant::getNullValue(Op0->getType());
2196
2197 const APInt *C1;
2198 Value *A;
2199 // (A ^ C) & (A ^ ~C) -> 0
2200 if (match(Op0, m_Xor(m_Value(A), m_APInt(C1))) &&
2201 match(Op1, m_Xor(m_Specific(A), m_SpecificInt(~*C1))))
2202 return Constant::getNullValue(Op0->getType());
2203
2204 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2205 if (std::optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
2206 // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2207 if (*Implied == true)
2208 return Op0;
2209 // If Op0 is true implies Op1 is false, then they are not true together.
2210 if (*Implied == false)
2211 return ConstantInt::getFalse(Op0->getType());
2212 }
2213 if (std::optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
2214 // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2215 if (*Implied)
2216 return Op1;
2217 // If Op1 is true implies Op0 is false, then they are not true together.
2218 if (!*Implied)
2219 return ConstantInt::getFalse(Op1->getType());
2220 }
2221 }
2222
2223 if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2224 return V;
2225
2226 return nullptr;
2227}
2228
2230 return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
2231}
2232
2233// TODO: Many of these folds could use LogicalAnd/LogicalOr.
2235 assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2236 Type *Ty = X->getType();
2237
2238 // X | ~X --> -1
2239 if (match(Y, m_Not(m_Specific(X))))
2241
2242 // X | ~(X & ?) = -1
2243 if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2245
2246 // X | (X & ?) --> X
2247 if (match(Y, m_c_And(m_Specific(X), m_Value())))
2248 return X;
2249
2250 Value *A, *B;
2251
2252 // (A ^ B) | (A | B) --> A | B
2253 // (A ^ B) | (B | A) --> B | A
2254 if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2256 return Y;
2257
2258 // ~(A ^ B) | (A | B) --> -1
2259 // ~(A ^ B) | (B | A) --> -1
2260 if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2263
2264 // (A & ~B) | (A ^ B) --> A ^ B
2265 // (~B & A) | (A ^ B) --> A ^ B
2266 // (A & ~B) | (B ^ A) --> B ^ A
2267 // (~B & A) | (B ^ A) --> B ^ A
2268 if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2270 return Y;
2271
2272 // (~A ^ B) | (A & B) --> ~A ^ B
2273 // (B ^ ~A) | (A & B) --> B ^ ~A
2274 // (~A ^ B) | (B & A) --> ~A ^ B
2275 // (B ^ ~A) | (B & A) --> B ^ ~A
2276 if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2278 return X;
2279
2280 // (~A | B) | (A ^ B) --> -1
2281 // (~A | B) | (B ^ A) --> -1
2282 // (B | ~A) | (A ^ B) --> -1
2283 // (B | ~A) | (B ^ A) --> -1
2284 if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2287
2288 // (~A & B) | ~(A | B) --> ~A
2289 // (~A & B) | ~(B | A) --> ~A
2290 // (B & ~A) | ~(A | B) --> ~A
2291 // (B & ~A) | ~(B | A) --> ~A
2292 Value *NotA;
2294 m_Value(B))) &&
2296 return NotA;
2297 // The same is true of Logical And
2298 // TODO: This could share the logic of the version above if there was a
2299 // version of LogicalAnd that allowed more than just i1 types.
2301 m_Value(B))) &&
2303 return NotA;
2304
2305 // ~(A ^ B) | (A & B) --> ~(A ^ B)
2306 // ~(A ^ B) | (B & A) --> ~(A ^ B)
2307 Value *NotAB;
2309 m_Value(NotAB))) &&
2311 return NotAB;
2312
2313 // ~(A & B) | (A ^ B) --> ~(A & B)
2314 // ~(A & B) | (B ^ A) --> ~(A & B)
2316 m_Value(NotAB))) &&
2318 return NotAB;
2319
2320 return nullptr;
2321}
2322
2323/// Given operands for an Or, see if we can fold the result.
2324/// If not, this returns null.
2325static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2326 unsigned MaxRecurse) {
2327 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2328 return C;
2329
2330 // X | poison -> poison
2331 if (isa<PoisonValue>(Op1))
2332 return Op1;
2333
2334 // X | undef -> -1
2335 // X | -1 = -1
2336 // Do not return Op1 because it may contain undef elements if it's a vector.
2337 if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2338 return Constant::getAllOnesValue(Op0->getType());
2339
2340 // X | X = X
2341 // X | 0 = X
2342 if (Op0 == Op1 || match(Op1, m_Zero()))
2343 return Op0;
2344
2345 if (Value *R = simplifyOrLogic(Op0, Op1))
2346 return R;
2347 if (Value *R = simplifyOrLogic(Op1, Op0))
2348 return R;
2349
2350 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2351 return V;
2352
2353 // Rotated -1 is still -1:
2354 // (-1 << X) | (-1 >> (C - X)) --> -1
2355 // (-1 >> X) | (-1 << (C - X)) --> -1
2356 // ...with C <= bitwidth (and commuted variants).
2357 Value *X, *Y;
2358 if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2359 match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2360 (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2361 match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2362 const APInt *C;
2363 if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2364 match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2365 C->ule(X->getType()->getScalarSizeInBits())) {
2366 return ConstantInt::getAllOnesValue(X->getType());
2367 }
2368 }
2369
2370 // zext(X) | sext(X) --> sext(X)
2371 // sext(X) | zext(X) --> sext(X)
2372 {
2373 Value *X = nullptr;
2374 if (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Specific(X))))
2375 return Op1;
2376 if (match(Op1, m_ZExt(m_Value(X))) && match(Op0, m_SExt(m_Specific(X))))
2377 return Op0;
2378 }
2379
2380 // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2381 // are mixing in another shift that is redundant with the funnel shift.
2382
2383 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2384 // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2385 if (match(Op0,
2387 match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2388 return Op0;
2389 if (match(Op1,
2391 match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2392 return Op1;
2393
2394 // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2395 // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2396 if (match(Op0,
2398 match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2399 return Op0;
2400 if (match(Op1,
2402 match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2403 return Op1;
2404
2405 if (Value *V =
2406 simplifyAndOrWithICmpEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2407 return V;
2408 if (Value *V =
2409 simplifyAndOrWithICmpEq(Instruction::Or, Op1, Op0, Q, MaxRecurse))
2410 return V;
2411
2412 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2413 return V;
2414
2415 // If we have a multiplication overflow check that is being 'and'ed with a
2416 // check that one of the multipliers is not zero, we can omit the 'and', and
2417 // only keep the overflow check.
2418 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2419 return Op1;
2420 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2421 return Op0;
2422
2423 // Try some generic simplifications for associative operations.
2424 if (Value *V =
2425 simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2426 return V;
2427
2428 // Or distributes over And. Try some generic simplifications based on this.
2429 if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2430 Instruction::And, Q, MaxRecurse))
2431 return V;
2432
2433 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2434 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2435 // A | (A || B) -> A || B
2436 if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2437 return Op1;
2438 else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2439 return Op0;
2440 }
2441 // If the operation is with the result of a select instruction, check
2442 // whether operating on either branch of the select always yields the same
2443 // value.
2444 if (Value *V =
2445 threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2446 return V;
2447 }
2448
2449 // (A & C1)|(B & C2)
2450 Value *A, *B;
2451 const APInt *C1, *C2;
2452 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2453 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2454 if (*C1 == ~*C2) {
2455 // (A & C1)|(B & C2)
2456 // If we have: ((V + N) & C1) | (V & C2)
2457 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2458 // replace with V+N.
2459 Value *N;
2460 if (C2->isMask() && // C2 == 0+1+
2462 // Add commutes, try both ways.
2463 if (MaskedValueIsZero(N, *C2, Q))
2464 return A;
2465 }
2466 // Or commutes, try both ways.
2467 if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2468 // Add commutes, try both ways.
2469 if (MaskedValueIsZero(N, *C1, Q))
2470 return B;
2471 }
2472 }
2473 }
2474
2475 // If the operation is with the result of a phi instruction, check whether
2476 // operating on all incoming values of the phi always yields the same value.
2477 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2478 if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2479 return V;
2480
2481 // (A ^ C) | (A ^ ~C) -> -1, i.e. all bits set to one.
2482 if (match(Op0, m_Xor(m_Value(A), m_APInt(C1))) &&
2483 match(Op1, m_Xor(m_Specific(A), m_SpecificInt(~*C1))))
2484 return Constant::getAllOnesValue(Op0->getType());
2485
2486 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2487 if (std::optional<bool> Implied =
2488 isImpliedCondition(Op0, Op1, Q.DL, false)) {
2489 // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2490 if (*Implied == false)
2491 return Op0;
2492 // If Op0 is false implies Op1 is true, then at least one is always true.
2493 if (*Implied == true)
2494 return ConstantInt::getTrue(Op0->getType());
2495 }
2496 if (std::optional<bool> Implied =
2497 isImpliedCondition(Op1, Op0, Q.DL, false)) {
2498 // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2499 if (*Implied == false)
2500 return Op1;
2501 // If Op1 is false implies Op0 is true, then at least one is always true.
2502 if (*Implied == true)
2503 return ConstantInt::getTrue(Op1->getType());
2504 }
2505 }
2506
2507 if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2508 return V;
2509
2510 return nullptr;
2511}
2512
2514 return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
2515}
2516
2517/// Given operands for a Xor, see if we can fold the result.
2518/// If not, this returns null.
2519static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2520 unsigned MaxRecurse) {
2521 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2522 return C;
2523
2524 // X ^ poison -> poison
2525 if (isa<PoisonValue>(Op1))
2526 return Op1;
2527
2528 // A ^ undef -> undef
2529 if (Q.isUndefValue(Op1))
2530 return Op1;
2531
2532 // A ^ 0 = A
2533 if (match(Op1, m_Zero()))
2534 return Op0;
2535
2536 // A ^ A = 0
2537 if (Op0 == Op1)
2538 return Constant::getNullValue(Op0->getType());
2539
2540 // A ^ ~A = ~A ^ A = -1
2541 if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2542 return Constant::getAllOnesValue(Op0->getType());
2543
2544 auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2545 Value *A, *B;
2546 // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2547 if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2549 return A;
2550
2551 // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2552 // The 'not' op must contain a complete -1 operand (no undef elements for
2553 // vector) for the transform to be safe.
2554 Value *NotA;
2556 m_Value(B))) &&
2558 return NotA;
2559
2560 return nullptr;
2561 };
2562 if (Value *R = foldAndOrNot(Op0, Op1))
2563 return R;
2564 if (Value *R = foldAndOrNot(Op1, Op0))
2565 return R;
2566
2567 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2568 return V;
2569
2570 // Try some generic simplifications for associative operations.
2571 if (Value *V =
2572 simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2573 return V;
2574
2575 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2576 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2577 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2578 // only if B and C are equal. If B and C are equal then (since we assume
2579 // that operands have already been simplified) "select(cond, B, C)" should
2580 // have been simplified to the common value of B and C already. Analysing
2581 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2582 // for threading over phi nodes.
2583
2584 if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2585 return V;
2586
2587 // (xor (sub nuw C_Mask, X), C_Mask) -> X
2588 {
2589 Value *X;
2590 if (match(Op0, m_NUWSub(m_Specific(Op1), m_Value(X))) &&
2591 match(Op1, m_LowBitMask()))
2592 return X;
2593 }
2594
2595 return nullptr;
2596}
2597
2599 return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
2600}
2601
2603 return CmpInst::makeCmpResultType(Op->getType());
2604}
2605
2606/// Rummage around inside V looking for something equivalent to the comparison
2607/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2608/// Helper function for analyzing max/min idioms.
2610 Value *LHS, Value *RHS) {
2612 if (!SI)
2613 return nullptr;
2614 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2615 if (!Cmp)
2616 return nullptr;
2617 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2618 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2619 return Cmp;
2620 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2621 LHS == CmpRHS && RHS == CmpLHS)
2622 return Cmp;
2623 return nullptr;
2624}
2625
2626static bool isByValArg(const Value *V) {
2627 const Argument *A = dyn_cast<Argument>(V);
2628 return A && A->hasByValAttr();
2629}
2630
2631static bool isDereferenceableArg(const Value *V) {
2632 const Argument *A = dyn_cast<Argument>(V);
2633 return A && A->getType()->isPointerTy() && A->getDereferenceableBytes() > 0;
2634}
2635
2636/// Return true if the underlying object (storage) must be disjoint from
2637/// storage returned by any noalias return call.
2638static bool isAllocDisjoint(const Value *V) {
2639 // For allocas, we consider only static ones (dynamic
2640 // allocas might be transformed into calls to malloc not simultaneously
2641 // live with the compared-to allocation). For globals, we exclude symbols
2642 // that might be resolve lazily to symbols in another dynamically-loaded
2643 // library (and, thus, could be malloc'ed by the implementation).
2644 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2645 return AI->isStaticAlloca();
2646 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2647 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2648 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2649 !GV->isThreadLocal();
2650 // Byval arguments point to storage accessible to the caller, which is
2651 // disjoint from the allocated storage returned by a noalias pointer.
2652 // TODO: possibly extend this to `dereferenceable(N)` arguments once the LLVM
2653 // allocator model and its interaction with `noalias` on return values is
2654 // clarified.
2655 return isByValArg(V);
2656}
2657
2658/// Return true if V1 and V2 are each the base of some distict storage region
2659/// [V, object_size(V)] which do not overlap. Note that zero sized regions
2660/// *are* possible, and that zero sized regions do not overlap with any other.
2661static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2662 // Global variables always exist, so they always exist during the lifetime
2663 // of each other and all allocas. Global variables themselves usually have
2664 // non-overlapping storage, but since their addresses are constants, the
2665 // case involving two globals does not reach here and is instead handled in
2666 // constant folding.
2667 //
2668 // Two different allocas usually have different addresses...
2669 //
2670 // However, if there's an @llvm.stackrestore dynamically in between two
2671 // allocas, they may have the same address. It's tempting to reduce the
2672 // scope of the problem by only looking at *static* allocas here. That would
2673 // cover the majority of allocas while significantly reducing the likelihood
2674 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2675 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2676 // an entry block. Also, if we have a block that's not attached to a
2677 // function, we can't tell if it's "static" under the current definition.
2678 // Theoretically, this problem could be fixed by creating a new kind of
2679 // instruction kind specifically for static allocas. Such a new instruction
2680 // could be required to be at the top of the entry block, thus preventing it
2681 // from being subject to a @llvm.stackrestore. Instcombine could even
2682 // convert regular allocas into these special allocas. It'd be nifty.
2683 // However, until then, this problem remains open.
2684 //
2685 // So, we'll assume that two non-empty allocas have different addresses
2686 // for now.
2687 //
2688 // Furthermore, an argument marked with the `dereferenceable(N)` attribute is
2689 // guaranteed to point to N loadable bytes. Such a pointer cannot be a
2690 // one-past-the-end pointer whose address happens to coincide with the start
2691 // of another object (e.g., an alloca), as loading from a one-past-the-end
2692 // address would be UB (thus, in contrast with the premise).
2693
2694 // Byval args are backed by storage that does not overlap with allocas,
2695 // globals, other byval args, or any dereferenceable argument.
2696 if (isByValArg(V1))
2697 return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2) ||
2699 if (isByValArg(V2))
2702
2703 if ((isDereferenceableArg(V1) && isa<AllocaInst>(V2)) ||
2705 return true;
2706
2707 return isa<AllocaInst>(V1) &&
2709}
2710
2711// A significant optimization not implemented here is assuming that alloca
2712// addresses are not equal to incoming argument values. They don't *alias*,
2713// as we say, but that doesn't mean they aren't equal, so we take a
2714// conservative approach.
2715//
2716// This is inspired in part by C++11 5.10p1:
2717// "Two pointers of the same type compare equal if and only if they are both
2718// null, both point to the same function, or both represent the same
2719// address."
2720//
2721// This is pretty permissive.
2722//
2723// It's also partly due to C11 6.5.9p6:
2724// "Two pointers compare equal if and only if both are null pointers, both are
2725// pointers to the same object (including a pointer to an object and a
2726// subobject at its beginning) or function, both are pointers to one past the
2727// last element of the same array object, or one is a pointer to one past the
2728// end of one array object and the other is a pointer to the start of a
2729// different array object that happens to immediately follow the first array
2730// object in the address space.)
2731//
2732// C11's version is more restrictive, however there's no reason why an argument
2733// couldn't be a one-past-the-end value for a stack object in the caller and be
2734// equal to the beginning of a stack object in the callee.
2735//
2736// If the C and C++ standards are ever made sufficiently restrictive in this
2737// area, it may be possible to update LLVM's semantics accordingly and reinstate
2738// this optimization.
2740 const SimplifyQuery &Q) {
2741 assert(LHS->getType() == RHS->getType() && "Must have same types");
2742 const DataLayout &DL = Q.DL;
2743
2744 // We fold equality and unsigned predicates on pointer comparisons, but forbid
2745 // signed predicates since a GEP with inbounds could cross the sign boundary.
2747 return nullptr;
2748
2749 // We have to switch to a signed predicate to handle negative indices from
2750 // the base pointer.
2752
2753 // Strip off any constant offsets so that we can reason about them.
2754 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2755 // here and compare base addresses like AliasAnalysis does, however there are
2756 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2757 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2758 // doesn't need to guarantee pointer inequality when it says NoAlias.
2759
2760 // Even if an non-inbounds GEP occurs along the path we can still optimize
2761 // equality comparisons concerning the result.
2762 bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2763 unsigned IndexSize = DL.getIndexTypeSizeInBits(LHS->getType());
2764 APInt LHSOffset(IndexSize, 0), RHSOffset(IndexSize, 0);
2765 LHS = LHS->stripAndAccumulateConstantOffsets(DL, LHSOffset, AllowNonInbounds);
2766 RHS = RHS->stripAndAccumulateConstantOffsets(DL, RHSOffset, AllowNonInbounds);
2767
2768 // If LHS and RHS are related via constant offsets to the same base
2769 // value, we can replace it with an icmp which just compares the offsets.
2770 if (LHS == RHS)
2771 return ConstantInt::get(getCompareTy(LHS),
2772 ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2773
2774 // Various optimizations for (in)equality comparisons.
2776 // Different non-empty allocations that exist at the same time have
2777 // different addresses (if the program can tell). If the offsets are
2778 // within the bounds of their allocations (and not one-past-the-end,
2779 // so inbounds is not sufficient), and their allocations aren't the same,
2780 // the pointers are not equal.
2782 // Size of object V, falling back to `dereferenceable(N)` attribute on an
2783 // argument when getObjectSize cannot determine a concrete size.
2784 auto GetKnownSize = [&](Value *V, uint64_t &Size) {
2785 bool CanBeNull;
2786 Size = V->getPointerDereferenceableBytes(DL, CanBeNull,
2787 /*CanBeFreed=*/nullptr);
2788 return Size != 0 && !CanBeNull;
2789 };
2790
2791 uint64_t LHSSize, RHSSize;
2792 if (GetKnownSize(LHS, LHSSize) && GetKnownSize(RHS, RHSSize)) {
2793 APInt Dist = LHSOffset - RHSOffset;
2794 if (Dist.isNonNegative() ? Dist.ult(LHSSize) : (-Dist).ult(RHSSize))
2795 return ConstantInt::get(getCompareTy(LHS),
2797 }
2798 }
2799
2800 // If one side of the equality comparison must come from a noalias call
2801 // (meaning a system memory allocation function), and the other side must
2802 // come from a pointer that cannot overlap with dynamically-allocated
2803 // memory within the lifetime of the current function (allocas, byval
2804 // arguments, globals), then determine the comparison result here.
2805 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2806 getUnderlyingObjects(LHS, LHSUObjs);
2807 getUnderlyingObjects(RHS, RHSUObjs);
2808
2809 // Is the set of underlying objects all noalias calls?
2810 auto IsNoAliasCall = [](ArrayRef<const Value *> Objects) {
2811 return all_of(Objects, isNoAliasCall);
2812 };
2813
2814 // Is the set of underlying objects all things which must be disjoint from
2815 // noalias calls. We assume that indexing from such disjoint storage
2816 // into the heap is undefined, and thus offsets can be safely ignored.
2817 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2818 return all_of(Objects, ::isAllocDisjoint);
2819 };
2820
2821 if ((IsNoAliasCall(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2822 (IsNoAliasCall(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2823 return ConstantInt::get(getCompareTy(LHS),
2825
2826 // Fold comparisons for non-escaping pointer even if the allocation call
2827 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2828 // dynamic allocation call could be either of the operands. Note that
2829 // the other operand can not be based on the alloc - if it were, then
2830 // the cmp itself would be a capture.
2831 Value *MI = nullptr;
2833 MI = LHS;
2834 else if (isAllocLikeFn(RHS) && llvm::isKnownNonZero(LHS, Q))
2835 MI = RHS;
2836 if (MI) {
2837 // FIXME: This is incorrect, see PR54002. While we can assume that the
2838 // allocation is at an address that makes the comparison false, this
2839 // requires that *all* comparisons to that address be false, which
2840 // InstSimplify cannot guarantee.
2841 struct CustomCaptureTracker : public CaptureTracker {
2842 bool Captured = false;
2843 void tooManyUses() override { Captured = true; }
2844 Action captured(const Use *U, UseCaptureInfo CI) override {
2845 // TODO(captures): Use UseCaptureInfo.
2846 if (auto *ICmp = dyn_cast<ICmpInst>(U->getUser())) {
2847 // Comparison against value stored in global variable. Given the
2848 // pointer does not escape, its value cannot be guessed and stored
2849 // separately in a global variable.
2850 unsigned OtherIdx = 1 - U->getOperandNo();
2851 auto *LI = dyn_cast<LoadInst>(ICmp->getOperand(OtherIdx));
2852 if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
2853 return Continue;
2854 }
2855
2856 Captured = true;
2857 return Stop;
2858 }
2859 };
2860 CustomCaptureTracker Tracker;
2861 PointerMayBeCaptured(MI, &Tracker);
2862 if (!Tracker.Captured)
2863 return ConstantInt::get(getCompareTy(LHS),
2865 }
2866 }
2867
2868 // Otherwise, fail.
2869 return nullptr;
2870}
2871
2872/// Fold an icmp when its operands have i1 scalar type.
2874 const SimplifyQuery &Q) {
2875 Type *ITy = getCompareTy(LHS); // The return type.
2876 Type *OpTy = LHS->getType(); // The operand type.
2877 if (!OpTy->isIntOrIntVectorTy(1))
2878 return nullptr;
2879
2880 // A boolean compared to true/false can be reduced in 14 out of the 20
2881 // (10 predicates * 2 constants) possible combinations. The other
2882 // 6 cases require a 'not' of the LHS.
2883
2884 auto ExtractNotLHS = [](Value *V) -> Value * {
2885 Value *X;
2886 if (match(V, m_Not(m_Value(X))))
2887 return X;
2888 return nullptr;
2889 };
2890
2891 if (match(RHS, m_Zero())) {
2892 switch (Pred) {
2893 case CmpInst::ICMP_NE: // X != 0 -> X
2894 case CmpInst::ICMP_UGT: // X >u 0 -> X
2895 case CmpInst::ICMP_SLT: // X <s 0 -> X
2896 return LHS;
2897
2898 case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X
2899 case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2900 case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2901 if (Value *X = ExtractNotLHS(LHS))
2902 return X;
2903 break;
2904
2905 case CmpInst::ICMP_ULT: // X <u 0 -> false
2906 case CmpInst::ICMP_SGT: // X >s 0 -> false
2907 return getFalse(ITy);
2908
2909 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2910 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2911 return getTrue(ITy);
2912
2913 default:
2914 break;
2915 }
2916 } else if (match(RHS, m_One())) {
2917 switch (Pred) {
2918 case CmpInst::ICMP_EQ: // X == 1 -> X
2919 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2920 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2921 return LHS;
2922
2923 case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X
2924 case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X
2925 case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X
2926 if (Value *X = ExtractNotLHS(LHS))
2927 return X;
2928 break;
2929
2930 case CmpInst::ICMP_UGT: // X >u 1 -> false
2931 case CmpInst::ICMP_SLT: // X <s -1 -> false
2932 return getFalse(ITy);
2933
2934 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2935 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2936 return getTrue(ITy);
2937
2938 default:
2939 break;
2940 }
2941 }
2942
2943 switch (Pred) {
2944 default:
2945 break;
2946 case ICmpInst::ICMP_UGE:
2947 if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2948 return getTrue(ITy);
2949 break;
2950 case ICmpInst::ICMP_SGE:
2951 /// For signed comparison, the values for an i1 are 0 and -1
2952 /// respectively. This maps into a truth table of:
2953 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2954 /// 0 | 0 | 1 (0 >= 0) | 1
2955 /// 0 | 1 | 1 (0 >= -1) | 1
2956 /// 1 | 0 | 0 (-1 >= 0) | 0
2957 /// 1 | 1 | 1 (-1 >= -1) | 1
2958 if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2959 return getTrue(ITy);
2960 break;
2961 case ICmpInst::ICMP_ULE:
2962 if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2963 return getTrue(ITy);
2964 break;
2965 case ICmpInst::ICMP_SLE:
2966 /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2967 if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2968 return getTrue(ITy);
2969 break;
2970 }
2971
2972 return nullptr;
2973}
2974
2975/// Check if RHS is zero or can be transformed to an equivalent zero comparison.
2976/// E.g., icmp sgt X, -1 --> icmp sge X, 0
2978 // icmp [pred] X, 0 --> as-is
2979 if (match(RHS, m_Zero()))
2980 return true;
2981
2982 // Handle comparisons with -1 (all ones)
2983 if (match(RHS, m_AllOnes())) {
2984 switch (Pred) {
2985 case ICmpInst::ICMP_SGT:
2986 // icmp sgt X, -1 --> icmp sge X, 0
2988 return true;
2989 case ICmpInst::ICMP_SLE:
2990 // icmp sle X, -1 --> icmp slt X, 0
2992 return true;
2993 // Note: unsigned comparisons with -1 (UINT_MAX) are not handled here:
2994 // - icmp ugt X, -1 is always false (nothing > UINT_MAX)
2995 // - icmp ule X, -1 is always true (everything <= UINT_MAX)
2996 default:
2997 return false;
2998 }
2999 }
3000
3001 // Handle comparisons with 1
3002 if (match(RHS, m_One())) {
3003 switch (Pred) {
3004 case ICmpInst::ICMP_SGE:
3005 // icmp sge X, 1 --> icmp sgt X, 0
3007 return true;
3008 case ICmpInst::ICMP_UGE:
3009 // icmp uge X, 1 --> icmp ugt X, 0
3011 return true;
3012 case ICmpInst::ICMP_SLT:
3013 // icmp slt X, 1 --> icmp sle X, 0
3015 return true;
3016 case ICmpInst::ICMP_ULT:
3017 // icmp ult X, 1 --> icmp ule X, 0
3019 return true;
3020 default:
3021 return false;
3022 }
3023 }
3024
3025 return false;
3026}
3027
3028/// Try hard to fold icmp with zero RHS because this is a common case.
3029/// Note that, this function also handles the equivalent zero RHS, e.g.,
3030/// icmp sgt X, -1 --> icmp sge X, 0
3032 const SimplifyQuery &Q) {
3033 // Check if RHS is zero or can be transformed to an equivalent zero comparison
3034 if (!matchEquivZeroRHS(Pred, RHS))
3035 return nullptr;
3036
3037 Type *ITy = getCompareTy(LHS); // The return type.
3038 switch (Pred) {
3039 default:
3040 llvm_unreachable("Unknown ICmp predicate!");
3041 case ICmpInst::ICMP_ULT:
3042 return getFalse(ITy);
3043 case ICmpInst::ICMP_UGE:
3044 return getTrue(ITy);
3045 case ICmpInst::ICMP_EQ:
3046 case ICmpInst::ICMP_ULE:
3047 if (isKnownNonZero(LHS, Q))
3048 return getFalse(ITy);
3049 break;
3050 case ICmpInst::ICMP_NE:
3051 case ICmpInst::ICMP_UGT:
3052 if (isKnownNonZero(LHS, Q))
3053 return getTrue(ITy);
3054 break;
3055 case ICmpInst::ICMP_SLT: {
3056 KnownBits LHSKnown = computeKnownBits(LHS, Q);
3057 if (LHSKnown.isNegative())
3058 return getTrue(ITy);
3059 if (LHSKnown.isNonNegative())
3060 return getFalse(ITy);
3061 break;
3062 }
3063 case ICmpInst::ICMP_SLE: {
3064 KnownBits LHSKnown = computeKnownBits(LHS, Q);
3065 if (LHSKnown.isNegative())
3066 return getTrue(ITy);
3067 if (LHSKnown.isNonNegative() && isKnownNonZero(LHS, Q))
3068 return getFalse(ITy);
3069 break;
3070 }
3071 case ICmpInst::ICMP_SGE: {
3072 KnownBits LHSKnown = computeKnownBits(LHS, Q);
3073 if (LHSKnown.isNegative())
3074 return getFalse(ITy);
3075 if (LHSKnown.isNonNegative())
3076 return getTrue(ITy);
3077 break;
3078 }
3079 case ICmpInst::ICMP_SGT: {
3080 KnownBits LHSKnown = computeKnownBits(LHS, Q);
3081 if (LHSKnown.isNegative())
3082 return getFalse(ITy);
3083 if (LHSKnown.isNonNegative() && isKnownNonZero(LHS, Q))
3084 return getTrue(ITy);
3085 break;
3086 }
3087 }
3088
3089 return nullptr;
3090}
3091
3093 Value *RHS, const SimplifyQuery &Q) {
3094 Type *ITy = getCompareTy(RHS); // The return type.
3095
3096 Value *X;
3097 const APInt *C;
3098 if (!match(RHS, m_APIntAllowPoison(C)))
3099 return nullptr;
3100
3101 // Sign-bit checks can be optimized to true/false after unsigned
3102 // floating-point casts:
3103 // icmp slt (bitcast (uitofp X)), 0 --> false
3104 // icmp sgt (bitcast (uitofp X)), -1 --> true
3106 bool TrueIfSigned;
3107 if (isSignBitCheck(Pred, *C, TrueIfSigned))
3108 return ConstantInt::getBool(ITy, !TrueIfSigned);
3109 }
3110
3111 // Rule out tautological comparisons (eg., ult 0 or uge 0).
3113 if (RHS_CR.isEmptySet())
3114 return ConstantInt::getFalse(ITy);
3115 if (RHS_CR.isFullSet())
3116 return ConstantInt::getTrue(ITy);
3117
3119 if (!LHS_CR.isFullSet()) {
3120 if (RHS_CR.contains(LHS_CR))
3121 return ConstantInt::getTrue(ITy);
3122 if (RHS_CR.inverse().contains(LHS_CR))
3123 return ConstantInt::getFalse(ITy);
3124 }
3125
3126 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC)
3127 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3128 const APInt *MulC;
3131 *MulC != 0 && C->urem(*MulC) != 0) ||
3133 *MulC != 0 && C->srem(*MulC) != 0)))
3134 return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
3135
3136 if (Pred == ICmpInst::ICMP_UGE && C->isOne() && isKnownNonZero(LHS, Q))
3137 return ConstantInt::getTrue(ITy);
3138
3139 return nullptr;
3140}
3141
3143
3144/// Get values V_i such that V uge V_i (GreaterEq) or V ule V_i (LowerEq).
3147 const SimplifyQuery &Q,
3148 unsigned Depth = 0) {
3149 if (!Res.insert(V).second)
3150 return;
3151
3152 // Can be increased if useful.
3153 if (++Depth > 1)
3154 return;
3155
3156 auto *I = dyn_cast<Instruction>(V);
3157 if (!I)
3158 return;
3159
3160 Value *X, *Y;
3162 if (match(I, m_Or(m_Value(X), m_Value(Y))) ||
3166 }
3167 // X * Y >= X --> true
3168 if (match(I, m_NUWMul(m_Value(X), m_Value(Y)))) {
3169 if (isKnownNonZero(X, Q))
3171 if (isKnownNonZero(Y, Q))
3173 }
3174 } else {
3176 switch (I->getOpcode()) {
3177 case Instruction::And:
3178 getUnsignedMonotonicValues(Res, I->getOperand(0), Type, Q, Depth);
3179 getUnsignedMonotonicValues(Res, I->getOperand(1), Type, Q, Depth);
3180 break;
3181 case Instruction::URem:
3182 case Instruction::UDiv:
3183 case Instruction::LShr:
3184 getUnsignedMonotonicValues(Res, I->getOperand(0), Type, Q, Depth);
3185 break;
3186 case Instruction::Call:
3187 // usub.sat(X, Y) ule X, ctpop(X) ule X
3189 match(I, m_Ctpop(m_Value(X))))
3191 break;
3192 default:
3193 break;
3194 }
3195 }
3196}
3197
3199 Value *RHS,
3200 const SimplifyQuery &Q) {
3202 return nullptr;
3203
3204 // We have LHS uge GreaterValues and LowerValues uge RHS. If any of the
3205 // GreaterValues and LowerValues are the same, it follows that LHS uge RHS.
3206 SmallPtrSet<Value *, 4> GreaterValues;
3207 SmallPtrSet<Value *, 4> LowerValues;
3210 for (Value *GV : GreaterValues)
3211 if (LowerValues.contains(GV))
3214 return nullptr;
3215}
3216
3218 Value *RHS, const SimplifyQuery &Q,
3219 unsigned MaxRecurse) {
3220 Type *ITy = getCompareTy(RHS); // The return type.
3221
3222 Value *Y = nullptr;
3223 // icmp pred (or X, Y), X
3224 if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3226 KnownBits RHSKnown = computeKnownBits(RHS, Q);
3227 KnownBits YKnown = computeKnownBits(Y, Q);
3228 if (RHSKnown.isNonNegative() && YKnown.isNegative())
3229 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3230 if (RHSKnown.isNegative() || YKnown.isNonNegative())
3231 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3232 }
3233 }
3234
3235 // icmp pred (urem X, Y), Y
3236 if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3237 switch (Pred) {
3238 default:
3239 break;
3240 case ICmpInst::ICMP_SGT:
3241 case ICmpInst::ICMP_SGE: {
3243 if (!Known.isNonNegative())
3244 break;
3245 [[fallthrough]];
3246 }
3247 case ICmpInst::ICMP_EQ:
3248 case ICmpInst::ICMP_UGT:
3249 case ICmpInst::ICMP_UGE:
3250 return getFalse(ITy);
3251 case ICmpInst::ICMP_SLT:
3252 case ICmpInst::ICMP_SLE: {
3254 if (!Known.isNonNegative())
3255 break;
3256 [[fallthrough]];
3257 }
3258 case ICmpInst::ICMP_NE:
3259 case ICmpInst::ICMP_ULT:
3260 case ICmpInst::ICMP_ULE:
3261 return getTrue(ITy);
3262 }
3263 }
3264
3265 // If x is nonzero:
3266 // x >>u C <u x --> true for C != 0.
3267 // x >>u C != x --> true for C != 0.
3268 // x >>u C >=u x --> false for C != 0.
3269 // x >>u C == x --> false for C != 0.
3270 // x udiv C <u x --> true for C != 1.
3271 // x udiv C != x --> true for C != 1.
3272 // x udiv C >=u x --> false for C != 1.
3273 // x udiv C == x --> false for C != 1.
3274 // TODO: allow non-constant shift amount/divisor
3275 const APInt *C;
3276 if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3277 (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3278 if (isKnownNonZero(RHS, Q)) {
3279 switch (Pred) {
3280 default:
3281 break;
3282 case ICmpInst::ICMP_EQ:
3283 case ICmpInst::ICMP_UGE:
3284 case ICmpInst::ICMP_UGT:
3285 return getFalse(ITy);
3286 case ICmpInst::ICMP_NE:
3287 case ICmpInst::ICMP_ULT:
3288 case ICmpInst::ICMP_ULE:
3289 return getTrue(ITy);
3290 }
3291 }
3292 }
3293
3294 // (x+C1)/C2 <= x for C1 < C2.
3295 // This holds even if the addition overflows. Assume arithmetic modulo
3296 // M, then when overflow occurs the numerator is `x+C1-M` or equivalently
3297 // `C1-(M-x)`. Because `x < M`, we have that `C1-(M-x) < C1 < C2`. Hence the
3298 // result of the division on overflow is always 0, and `0 <= x`.
3299 //
3300 // If the addition does not overflow, the unrounded result of the division
3301 // is the sum of x/C2 (at most x) and C1/C2 (less than one because C1<C2).
3302 // Their sum is therefore strictly less than x+1, and rounding down to
3303 // an integer gives a value of at most x.
3304 //
3305 // Additionally, the division might be represented as a shift.
3306 const APInt *C1, *C2;
3307 if ((match(LBO, m_UDiv(m_Add(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3308 C1->ult(*C2)) ||
3309 (match(LBO, m_LShr(m_Add(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3310 C1->ult(APInt(C2->getBitWidth(), 1) << *C2))) {
3311 if (Pred == ICmpInst::ICMP_UGT)
3312 return getFalse(ITy);
3313 if (Pred == ICmpInst::ICMP_ULE)
3314 return getTrue(ITy);
3315 }
3316
3317 // (x*C1)/C2 <= x for C1 <= C2.
3318 // This holds even if the multiplication overflows: Assume that x != 0 and
3319 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3320 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3321 //
3322 // Additionally, either the multiplication and division might be represented
3323 // as shifts:
3324 // (x*C1)>>C2 <= x for C1 < 2**C2.
3325 // (x<<C1)/C2 <= x for 2**C1 < C2.
3326 if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3327 C1->ule(*C2)) ||
3328 (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3329 C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3330 (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3331 (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3332 if (Pred == ICmpInst::ICMP_UGT)
3333 return getFalse(ITy);
3334 if (Pred == ICmpInst::ICMP_ULE)
3335 return getTrue(ITy);
3336 }
3337
3338 // (sub C, X) == X, C is odd --> false
3339 // (sub C, X) != X, C is odd --> true
3340 if (match(LBO, m_Sub(m_APIntAllowPoison(C), m_Specific(RHS))) &&
3341 (*C & 1) == 1 && ICmpInst::isEquality(Pred))
3342 return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
3343
3344 return nullptr;
3345}
3346
3347// If only one of the icmp's operands has NSW flags, try to prove that:
3348//
3349// icmp slt/sgt/sle/sge (x + C1), (x +nsw C2)
3350//
3351// is equivalent to:
3352//
3353// icmp slt/sgt/sle/sge C1, C2
3354//
3355// which is true if x + C2 has the NSW flags set and:
3356// *) C1 <= C2 && C1 >= 0, or
3357// *) C2 <= C1 && C1 <= 0.
3358//
3360 const InstrInfoQuery &IIQ) {
3361 // TODO: support other predicates.
3362 if (!ICmpInst::isSigned(Pred) || !IIQ.UseInstrInfo)
3363 return false;
3364
3365 // Canonicalize nsw add as RHS.
3366 if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3367 std::swap(LHS, RHS);
3368 if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3369 return false;
3370
3371 Value *X;
3372 const APInt *C1, *C2;
3373 if (!match(LHS, m_Add(m_Value(X), m_APInt(C1))) ||
3374 !match(RHS, m_Add(m_Specific(X), m_APInt(C2))))
3375 return false;
3376
3377 return (C1->sle(*C2) && C1->isNonNegative()) ||
3378 (C2->sle(*C1) && C1->isNonPositive());
3379}
3380
3381/// TODO: A large part of this logic is duplicated in InstCombine's
3382/// foldICmpBinOp(). We should be able to share that and avoid the code
3383/// duplication.
3385 const SimplifyQuery &Q,
3386 unsigned MaxRecurse) {
3389 if (MaxRecurse && (LBO || RBO)) {
3390 // Analyze the case when either LHS or RHS is an add instruction.
3391 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3392 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3393 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3394 if (LBO && LBO->getOpcode() == Instruction::Add) {
3395 A = LBO->getOperand(0);
3396 B = LBO->getOperand(1);
3397 NoLHSWrapProblem =
3403 }
3404 if (RBO && RBO->getOpcode() == Instruction::Add) {
3405 C = RBO->getOperand(0);
3406 D = RBO->getOperand(1);
3407 NoRHSWrapProblem =
3413 }
3414
3415 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3416 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3417 if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
3418 Constant::getNullValue(RHS->getType()), Q,
3419 MaxRecurse - 1))
3420 return V;
3421
3422 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3423 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3424 if (Value *V =
3426 C == LHS ? D : C, Q, MaxRecurse - 1))
3427 return V;
3428
3429 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3430 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3432 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3433 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3434 Value *Y, *Z;
3435 if (A == C) {
3436 // C + B == C + D -> B == D
3437 Y = B;
3438 Z = D;
3439 } else if (A == D) {
3440 // D + B == C + D -> B == C
3441 Y = B;
3442 Z = C;
3443 } else if (B == C) {
3444 // A + C == C + D -> A == D
3445 Y = A;
3446 Z = D;
3447 } else {
3448 assert(B == D);
3449 // A + D == C + D -> A == C
3450 Y = A;
3451 Z = C;
3452 }
3453 if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3454 return V;
3455 }
3456 }
3457
3458 if (LBO)
3459 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3460 return V;
3461
3462 if (RBO)
3464 ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3465 return V;
3466
3467 // 0 - (zext X) pred C
3469 const APInt *C;
3470 if (match(RHS, m_APInt(C))) {
3471 if (C->isStrictlyPositive()) {
3476 }
3477 if (C->isNonNegative()) {
3478 if (Pred == ICmpInst::ICMP_SLE)
3480 if (Pred == ICmpInst::ICMP_SGT)
3482 }
3483 }
3484 }
3485
3486 // If C2 is a power-of-2 and C is not:
3487 // (C2 << X) == C --> false
3488 // (C2 << X) != C --> true
3489 const APInt *C;
3490 if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3491 match(RHS, m_APIntAllowPoison(C)) && !C->isPowerOf2()) {
3492 // C2 << X can equal zero in some circumstances.
3493 // This simplification might be unsafe if C is zero.
3494 //
3495 // We know it is safe if:
3496 // - The shift is nsw. We can't shift out the one bit.
3497 // - The shift is nuw. We can't shift out the one bit.
3498 // - C2 is one.
3499 // - C isn't zero.
3502 match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3503 if (Pred == ICmpInst::ICMP_EQ)
3505 if (Pred == ICmpInst::ICMP_NE)
3507 }
3508 }
3509
3510 // If C is a power-of-2:
3511 // (C << X) >u 0x8000 --> false
3512 // (C << X) <=u 0x8000 --> true
3513 if (match(LHS, m_Shl(m_Power2(), m_Value())) && match(RHS, m_SignMask())) {
3514 if (Pred == ICmpInst::ICMP_UGT)
3516 if (Pred == ICmpInst::ICMP_ULE)
3518 }
3519
3520 if (!MaxRecurse || !LBO || !RBO || LBO->getOpcode() != RBO->getOpcode())
3521 return nullptr;
3522
3523 if (LBO->getOperand(0) == RBO->getOperand(0)) {
3524 switch (LBO->getOpcode()) {
3525 default:
3526 break;
3527 case Instruction::Shl: {
3528 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3529 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3530 if (!NUW || (ICmpInst::isSigned(Pred) && !NSW) ||
3531 !isKnownNonZero(LBO->getOperand(0), Q))
3532 break;
3533 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(1),
3534 RBO->getOperand(1), Q, MaxRecurse - 1))
3535 return V;
3536 break;
3537 }
3538 // If C1 & C2 == C1, A = X and/or C1, B = X and/or C2:
3539 // icmp ule A, B -> true
3540 // icmp ugt A, B -> false
3541 // icmp sle A, B -> true (C1 and C2 are the same sign)
3542 // icmp sgt A, B -> false (C1 and C2 are the same sign)
3543 case Instruction::And:
3544 case Instruction::Or: {
3545 const APInt *C1, *C2;
3547 match(LBO->getOperand(1), m_APInt(C1)) &&
3548 match(RBO->getOperand(1), m_APInt(C2))) {
3549 if (!C1->isSubsetOf(*C2)) {
3550 std::swap(C1, C2);
3552 }
3553 if (C1->isSubsetOf(*C2)) {
3554 if (Pred == ICmpInst::ICMP_ULE)
3556 if (Pred == ICmpInst::ICMP_UGT)
3558 if (C1->isNonNegative() == C2->isNonNegative()) {
3559 if (Pred == ICmpInst::ICMP_SLE)
3561 if (Pred == ICmpInst::ICMP_SGT)
3563 }
3564 }
3565 }
3566 break;
3567 }
3568 }
3569 }
3570
3571 if (LBO->getOperand(1) == RBO->getOperand(1)) {
3572 switch (LBO->getOpcode()) {
3573 default:
3574 break;
3575 case Instruction::UDiv:
3576 case Instruction::LShr:
3577 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3578 !Q.IIQ.isExact(RBO))
3579 break;
3580 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3581 RBO->getOperand(0), Q, MaxRecurse - 1))
3582 return V;
3583 break;
3584 case Instruction::SDiv:
3585 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3586 !Q.IIQ.isExact(RBO))
3587 break;
3588 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3589 RBO->getOperand(0), Q, MaxRecurse - 1))
3590 return V;
3591 break;
3592 case Instruction::AShr:
3593 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3594 break;
3595 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3596 RBO->getOperand(0), Q, MaxRecurse - 1))
3597 return V;
3598 break;
3599 case Instruction::Shl: {
3600 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3601 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3602 if (!NUW && !NSW)
3603 break;
3604 if (!NSW && ICmpInst::isSigned(Pred))
3605 break;
3606 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3607 RBO->getOperand(0), Q, MaxRecurse - 1))
3608 return V;
3609 break;
3610 }
3611 }
3612 }
3613 return nullptr;
3614}
3615
3616/// simplify integer comparisons where at least one operand of the compare
3617/// matches an integer min/max idiom.
3619 const SimplifyQuery &Q,
3620 unsigned MaxRecurse) {
3621 // All folds below need a min/max operand.
3623 return nullptr;
3624
3625 Type *ITy = getCompareTy(LHS); // The return type.
3626 Value *A, *B;
3628 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3629
3630 // Signed variants on "max(a,b)>=a -> true".
3631 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3632 if (A != RHS)
3633 std::swap(A, B); // smax(A, B) pred A.
3634 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3635 // We analyze this as smax(A, B) pred A.
3636 P = Pred;
3637 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3638 (A == LHS || B == LHS)) {
3639 if (A != LHS)
3640 std::swap(A, B); // A pred smax(A, B).
3641 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3642 // We analyze this as smax(A, B) swapped-pred A.
3644 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3645 (A == RHS || B == RHS)) {
3646 if (A != RHS)
3647 std::swap(A, B); // smin(A, B) pred A.
3648 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3649 // We analyze this as smax(-A, -B) swapped-pred -A.
3650 // Note that we do not need to actually form -A or -B thanks to EqP.
3652 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3653 (A == LHS || B == LHS)) {
3654 if (A != LHS)
3655 std::swap(A, B); // A pred smin(A, B).
3656 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3657 // We analyze this as smax(-A, -B) pred -A.
3658 // Note that we do not need to actually form -A or -B thanks to EqP.
3659 P = Pred;
3660 }
3662 // Cases correspond to "max(A, B) p A".
3663 switch (P) {
3664 default:
3665 break;
3666 case CmpInst::ICMP_EQ:
3667 case CmpInst::ICMP_SLE:
3668 // Equivalent to "A EqP B". This may be the same as the condition tested
3669 // in the max/min; if so, we can just return that.
3670 if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3671 return V;
3672 if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3673 return V;
3674 // Otherwise, see if "A EqP B" simplifies.
3675 if (MaxRecurse)
3676 if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3677 return V;
3678 break;
3679 case CmpInst::ICMP_NE:
3680 case CmpInst::ICMP_SGT: {
3682 // Equivalent to "A InvEqP B". This may be the same as the condition
3683 // tested in the max/min; if so, we can just return that.
3684 if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3685 return V;
3686 if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3687 return V;
3688 // Otherwise, see if "A InvEqP B" simplifies.
3689 if (MaxRecurse)
3690 if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3691 return V;
3692 break;
3693 }
3694 case CmpInst::ICMP_SGE:
3695 // Always true.
3696 return getTrue(ITy);
3697 case CmpInst::ICMP_SLT:
3698 // Always false.
3699 return getFalse(ITy);
3700 }
3701 }
3702
3703 // Unsigned variants on "max(a,b)>=a -> true".
3705 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3706 if (A != RHS)
3707 std::swap(A, B); // umax(A, B) pred A.
3708 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3709 // We analyze this as umax(A, B) pred A.
3710 P = Pred;
3711 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3712 (A == LHS || B == LHS)) {
3713 if (A != LHS)
3714 std::swap(A, B); // A pred umax(A, B).
3715 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3716 // We analyze this as umax(A, B) swapped-pred A.
3718 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3719 (A == RHS || B == RHS)) {
3720 if (A != RHS)
3721 std::swap(A, B); // umin(A, B) pred A.
3722 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3723 // We analyze this as umax(-A, -B) swapped-pred -A.
3724 // Note that we do not need to actually form -A or -B thanks to EqP.
3726 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3727 (A == LHS || B == LHS)) {
3728 if (A != LHS)
3729 std::swap(A, B); // A pred umin(A, B).
3730 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3731 // We analyze this as umax(-A, -B) pred -A.
3732 // Note that we do not need to actually form -A or -B thanks to EqP.
3733 P = Pred;
3734 }
3736 // Cases correspond to "max(A, B) p A".
3737 switch (P) {
3738 default:
3739 break;
3740 case CmpInst::ICMP_EQ:
3741 case CmpInst::ICMP_ULE:
3742 // Equivalent to "A EqP B". This may be the same as the condition tested
3743 // in the max/min; if so, we can just return that.
3744 if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3745 return V;
3746 if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3747 return V;
3748 // Otherwise, see if "A EqP B" simplifies.
3749 if (MaxRecurse)
3750 if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3751 return V;
3752 break;
3753 case CmpInst::ICMP_NE:
3754 case CmpInst::ICMP_UGT: {
3756 // Equivalent to "A InvEqP B". This may be the same as the condition
3757 // tested in the max/min; if so, we can just return that.
3758 if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3759 return V;
3760 if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3761 return V;
3762 // Otherwise, see if "A InvEqP B" simplifies.
3763 if (MaxRecurse)
3764 if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3765 return V;
3766 break;
3767 }
3768 case CmpInst::ICMP_UGE:
3769 return getTrue(ITy);
3770 case CmpInst::ICMP_ULT:
3771 return getFalse(ITy);
3772 }
3773 }
3774
3775 // Comparing 1 each of min/max with a common operand?
3776 // Canonicalize min operand to RHS.
3777 if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3778 match(LHS, m_SMin(m_Value(), m_Value()))) {
3779 std::swap(LHS, RHS);
3781 }
3782
3783 Value *C, *D;
3784 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3785 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3786 (A == C || A == D || B == C || B == D)) {
3787 // smax(A, B) >=s smin(A, D) --> true
3788 if (Pred == CmpInst::ICMP_SGE)
3789 return getTrue(ITy);
3790 // smax(A, B) <s smin(A, D) --> false
3791 if (Pred == CmpInst::ICMP_SLT)
3792 return getFalse(ITy);
3793 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3794 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3795 (A == C || A == D || B == C || B == D)) {
3796 // umax(A, B) >=u umin(A, D) --> true
3797 if (Pred == CmpInst::ICMP_UGE)
3798 return getTrue(ITy);
3799 // umax(A, B) <u umin(A, D) --> false
3800 if (Pred == CmpInst::ICMP_ULT)
3801 return getFalse(ITy);
3802 }
3803
3804 return nullptr;
3805}
3806
3808 Value *LHS, Value *RHS,
3809 const SimplifyQuery &Q) {
3810 // Gracefully handle instructions that have not been inserted yet.
3811 if (!Q.AC || !Q.CtxI)
3812 return nullptr;
3813
3814 for (Value *AssumeBaseOp : {LHS, RHS}) {
3815 for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3816 if (!AssumeVH)
3817 continue;
3818
3819 CallInst *Assume = cast<CallInst>(AssumeVH);
3820 if (std::optional<bool> Imp = isImpliedCondition(
3821 Assume->getArgOperand(0), Predicate, LHS, RHS, Q.DL))
3822 if (isValidAssumeForContext(Assume, Q))
3823 return ConstantInt::get(getCompareTy(LHS), *Imp);
3824 }
3825 }
3826
3827 return nullptr;
3828}
3829
3831 Value *RHS) {
3833 if (!II)
3834 return nullptr;
3835
3836 switch (II->getIntrinsicID()) {
3837 case Intrinsic::uadd_sat:
3838 // uadd.sat(X, Y) uge X + Y
3839 if (match(RHS, m_c_Add(m_Specific(II->getArgOperand(0)),
3840 m_Specific(II->getArgOperand(1))))) {
3841 if (Pred == ICmpInst::ICMP_UGE)
3843 if (Pred == ICmpInst::ICMP_ULT)
3845 }
3846 return nullptr;
3847 case Intrinsic::usub_sat:
3848 // usub.sat(X, Y) ule X - Y
3849 if (match(RHS, m_Sub(m_Specific(II->getArgOperand(0)),
3850 m_Specific(II->getArgOperand(1))))) {
3851 if (Pred == ICmpInst::ICMP_ULE)
3853 if (Pred == ICmpInst::ICMP_UGT)
3855 }
3856 return nullptr;
3857 default:
3858 return nullptr;
3859 }
3860}
3861
3862/// Helper method to get range from metadata or attribute.
3863static std::optional<ConstantRange> getRange(Value *V,
3864 const InstrInfoQuery &IIQ) {
3866 if (MDNode *MD = IIQ.getMetadata(I, LLVMContext::MD_range))
3867 return getConstantRangeFromMetadata(*MD);
3868
3869 if (const Argument *A = dyn_cast<Argument>(V))
3870 return A->getRange();
3871 else if (const CallBase *CB = dyn_cast<CallBase>(V))
3872 return CB->getRange();
3873
3874 return std::nullopt;
3875}
3876
3877/// Given operands for an ICmpInst, see if we can fold the result.
3878/// If not, this returns null.
3880 const SimplifyQuery &Q, unsigned MaxRecurse) {
3881 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3882
3883 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3884 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3885 if (Constant *C =
3886 ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI))
3887 return C;
3888 // Constant folding cannot always decide a comparison between constants.
3889 // Fall through to the generic logic below, which can still reason about
3890 // them with value tracking.
3891 } else {
3892 // If we have a constant, make sure it is on the RHS.
3893 std::swap(LHS, RHS);
3895 }
3896 }
3897 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3898
3899 Type *ITy = getCompareTy(LHS); // The return type.
3900
3901 // icmp poison, X -> poison
3902 if (isa<PoisonValue>(RHS))
3903 return PoisonValue::get(ITy);
3904
3905 // For EQ and NE, we can always pick a value for the undef to make the
3906 // predicate pass or fail, so we can return undef.
3907 // Matches behavior in llvm::ConstantFoldCompareInstruction.
3909 return UndefValue::get(ITy);
3910
3911 // icmp X, X -> true/false
3912 // icmp X, undef -> true/false because undef could be X.
3913 if (LHS == RHS || Q.isUndefValue(RHS))
3914 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3915
3916 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3917 return V;
3918
3919 // TODO: Sink/common this with other potentially expensive calls that use
3920 // ValueTracking? See comment below for isKnownNonEqual().
3921 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3922 return V;
3923
3925 return V;
3926
3927 // If both operands have range metadata, use the metadata
3928 // to simplify the comparison.
3929 if (std::optional<ConstantRange> RhsCr = getRange(RHS, Q.IIQ))
3930 if (std::optional<ConstantRange> LhsCr = getRange(LHS, Q.IIQ)) {
3931 if (LhsCr->icmp(Pred, *RhsCr))
3932 return ConstantInt::getTrue(ITy);
3933
3934 if (LhsCr->icmp(CmpInst::getInversePredicate(Pred), *RhsCr))
3935 return ConstantInt::getFalse(ITy);
3936 }
3937
3938 // Compare of cast, for example (zext X) != 0 -> X != 0
3941 Value *SrcOp = LI->getOperand(0);
3942 Type *SrcTy = SrcOp->getType();
3943 Type *DstTy = LI->getType();
3944
3945 // Turn icmp (ptrtoint/ptrtoaddr x), (ptrtoint/ptrtoaddr/constant) into a
3946 // compare of the input if the integer type is the same size as the
3947 // pointer address type (icmp only compares the address of the pointer).
3948 if (MaxRecurse && (isa<PtrToIntInst, PtrToAddrInst>(LI)) &&
3949 Q.DL.getAddressType(SrcTy) == DstTy) {
3950 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3951 // Transfer the cast to the constant.
3953 ConstantExpr::getIntToPtr(RHSC, SrcTy),
3954 Q, MaxRecurse - 1))
3955 return V;
3957 auto *RI = cast<CastInst>(RHS);
3958 if (RI->getOperand(0)->getType() == SrcTy)
3959 // Compare without the cast.
3960 if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3961 MaxRecurse - 1))
3962 return V;
3963 }
3964 }
3965
3966 if (isa<ZExtInst>(LHS)) {
3967 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3968 // same type.
3969 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3970 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3971 // Compare X and Y. Note that signed predicates become unsigned.
3972 if (Value *V =
3974 RI->getOperand(0), Q, MaxRecurse - 1))
3975 return V;
3976 }
3977 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3978 else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3979 if (SrcOp == RI->getOperand(0)) {
3981 return ConstantInt::getTrue(ITy);
3983 return ConstantInt::getFalse(ITy);
3984 }
3985 }
3986 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3987 // too. If not, then try to deduce the result of the comparison.
3988 else if (match(RHS, m_ImmConstant())) {
3990 assert(C != nullptr);
3991
3992 // Compute the constant that would happen if we truncated to SrcTy then
3993 // reextended to DstTy.
3994 Constant *Trunc =
3995 ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
3996 assert(Trunc && "Constant-fold of ImmConstant should not fail");
3997 Constant *RExt =
3998 ConstantFoldCastOperand(CastInst::ZExt, Trunc, DstTy, Q.DL);
3999 assert(RExt && "Constant-fold of ImmConstant should not fail");
4000 Constant *AnyEq =
4002 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
4003
4004 // If the re-extended constant didn't change any of the elements then
4005 // this is effectively also a case of comparing two zero-extended
4006 // values.
4007 if (AnyEq->isAllOnesValue() && MaxRecurse)
4009 SrcOp, Trunc, Q, MaxRecurse - 1))
4010 return V;
4011
4012 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
4013 // there. Use this to work out the result of the comparison.
4014 if (AnyEq->isNullValue()) {
4015 switch (Pred) {
4016 default:
4017 llvm_unreachable("Unknown ICmp predicate!");
4018 // LHS <u RHS.
4019 case ICmpInst::ICMP_EQ:
4020 case ICmpInst::ICMP_UGT:
4021 case ICmpInst::ICMP_UGE:
4022 return Constant::getNullValue(ITy);
4023
4024 case ICmpInst::ICMP_NE:
4025 case ICmpInst::ICMP_ULT:
4026 case ICmpInst::ICMP_ULE:
4027 return Constant::getAllOnesValue(ITy);
4028
4029 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
4030 // is non-negative then LHS <s RHS.
4031 case ICmpInst::ICMP_SGT:
4032 case ICmpInst::ICMP_SGE:
4035 Q.DL);
4036 case ICmpInst::ICMP_SLT:
4037 case ICmpInst::ICMP_SLE:
4040 Q.DL);
4041 }
4042 }
4043 }
4044 }
4045
4046 if (isa<SExtInst>(LHS)) {
4047 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
4048 // same type.
4049 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
4050 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
4051 // Compare X and Y. Note that the predicate does not change.
4052 if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
4053 MaxRecurse - 1))
4054 return V;
4055 }
4056 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
4057 else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
4058 if (SrcOp == RI->getOperand(0)) {
4060 return ConstantInt::getTrue(ITy);
4062 return ConstantInt::getFalse(ITy);
4063 }
4064 }
4065 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
4066 // too. If not, then try to deduce the result of the comparison.
4067 else if (match(RHS, m_ImmConstant())) {
4069
4070 // Compute the constant that would happen if we truncated to SrcTy then
4071 // reextended to DstTy.
4072 Constant *Trunc =
4073 ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
4074 assert(Trunc && "Constant-fold of ImmConstant should not fail");
4075 Constant *RExt =
4076 ConstantFoldCastOperand(CastInst::SExt, Trunc, DstTy, Q.DL);
4077 assert(RExt && "Constant-fold of ImmConstant should not fail");
4078 Constant *AnyEq =
4080 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
4081
4082 // If the re-extended constant didn't change then this is effectively
4083 // also a case of comparing two sign-extended values.
4084 if (AnyEq->isAllOnesValue() && MaxRecurse)
4085 if (Value *V =
4086 simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
4087 return V;
4088
4089 // Otherwise the upper bits of LHS are all equal, while RHS has varying
4090 // bits there. Use this to work out the result of the comparison.
4091 if (AnyEq->isNullValue()) {
4092 switch (Pred.getPreferredSignedPredicate()) {
4093 default:
4094 llvm_unreachable("Unknown ICmp predicate!");
4095 case ICmpInst::ICMP_EQ:
4096 return Constant::getNullValue(ITy);
4097 case ICmpInst::ICMP_NE:
4098 return Constant::getAllOnesValue(ITy);
4099
4100 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
4101 // LHS >s RHS.
4102 case ICmpInst::ICMP_SGT:
4103 case ICmpInst::ICMP_SGE:
4106 Q.DL);
4107 case ICmpInst::ICMP_SLT:
4108 case ICmpInst::ICMP_SLE:
4111 Q.DL);
4112
4113 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
4114 // LHS >u RHS.
4115 case ICmpInst::ICMP_UGT:
4116 case ICmpInst::ICMP_UGE:
4117 // Comparison is true iff the LHS <s 0.
4118 if (MaxRecurse)
4120 Constant::getNullValue(SrcTy), Q,
4121 MaxRecurse - 1))
4122 return V;
4123 break;
4124 case ICmpInst::ICMP_ULT:
4125 case ICmpInst::ICMP_ULE:
4126 // Comparison is true iff the LHS >=s 0.
4127 if (MaxRecurse)
4129 Constant::getNullValue(SrcTy), Q,
4130 MaxRecurse - 1))
4131 return V;
4132 break;
4133 }
4134 }
4135 }
4136 }
4137 }
4138
4139 // icmp eq|ne X, Y -> false|true if X != Y
4140 // This is potentially expensive, and we have already computedKnownBits for
4141 // compares with 0 above here, so only try this for a non-zero compare.
4142 if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
4143 isKnownNonEqual(LHS, RHS, Q)) {
4144 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
4145 }
4146
4147 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
4148 return V;
4149
4150 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
4151 return V;
4152
4154 return V;
4157 return V;
4158
4160 return V;
4163 return V;
4164
4166 return V;
4167
4168 if (std::optional<bool> Res =
4170 return ConstantInt::getBool(ITy, *Res);
4171
4172 // Simplify comparisons of related pointers using a powerful, recursive
4173 // GEP-walk when we have target data available..
4174 if (LHS->getType()->isPointerTy())
4175 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
4176 return C;
4177
4178 // If the comparison is with the result of a select instruction, check whether
4179 // comparing with either branch of the select always yields the same value.
4181 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4182 return V;
4183
4184 // If the comparison is with the result of a phi instruction, check whether
4185 // doing the compare with each incoming phi value yields a common result.
4187 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4188 return V;
4189
4190 return nullptr;
4191}
4192
4194 const SimplifyQuery &Q) {
4195 return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4196}
4197
4198/// Given operands for an FCmpInst, see if we can fold the result.
4199/// If not, this returns null.
4201 FastMathFlags FMF, const SimplifyQuery &Q,
4202 unsigned MaxRecurse) {
4203 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
4204
4205 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
4206 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
4207 // if the folding isn't successfull, fall back to the rest of the logic
4208 if (auto *Result = ConstantFoldCompareInstOperands(
4209 Pred, CLHS, CRHS, Q.DL, Q.TLI, Q.getFunction()))
4210 return Result;
4211 } else {
4212 // If we have a constant, make sure it is on the RHS.
4213 std::swap(LHS, RHS);
4215 }
4216 }
4217
4218 // Fold trivial predicates.
4219 Type *RetTy = getCompareTy(LHS);
4221 return getFalse(RetTy);
4223 return getTrue(RetTy);
4224
4225 // fcmp pred x, poison and fcmp pred poison, x
4226 // fold to poison
4228 return PoisonValue::get(RetTy);
4229
4230 // fcmp pred x, undef and fcmp pred undef, x
4231 // fold to true if unordered, false if ordered
4232 if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
4233 // Choosing NaN for the undef will always make unordered comparison succeed
4234 // and ordered comparison fail.
4235 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4236 }
4237
4238 // fcmp x,x -> true/false. Not all compares are foldable.
4239 if (LHS == RHS) {
4241 return getTrue(RetTy);
4243 return getFalse(RetTy);
4244 }
4245
4246 // Fold (un)ordered comparison if we can determine there are no NaNs.
4247 //
4248 // This catches the 2 variable input case, constants are handled below as a
4249 // class-like compare.
4253
4254 if (FMF.noNaNs() ||
4255 (RHSClass.isKnownNeverNaN() && LHSClass.isKnownNeverNaN()))
4256 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
4257
4258 if (RHSClass.isKnownAlwaysNaN() || LHSClass.isKnownAlwaysNaN())
4259 return ConstantInt::get(RetTy, Pred == CmpInst::FCMP_UNO);
4260 }
4261
4262 if (std::optional<bool> Res =
4264 return ConstantInt::getBool(RetTy, *Res);
4265
4266 const APFloat *C = nullptr;
4268 std::optional<KnownFPClass> FullKnownClassLHS;
4269
4270 // Lazily compute the possible classes for LHS. Avoid computing it twice if
4271 // RHS is a 0.
4272 auto computeLHSClass = [=, &FullKnownClassLHS](FPClassTest InterestedFlags =
4273 fcAllFlags) {
4274 if (FullKnownClassLHS)
4275 return *FullKnownClassLHS;
4276 return computeKnownFPClass(LHS, FMF, InterestedFlags, Q);
4277 };
4278
4279 if (C && Q.getFunction()) {
4280 // Fold out compares that express a class test.
4281 auto [ClassVal, ClassTest] =
4283 if (ClassVal) {
4284 FullKnownClassLHS = computeLHSClass();
4285 if ((FullKnownClassLHS->getKnownFPClasses() & ClassTest) == fcNone)
4286 return getFalse(RetTy);
4287 if ((FullKnownClassLHS->getKnownFPClasses() & ~ClassTest) == fcNone)
4288 return getTrue(RetTy);
4289 }
4290 }
4291
4292 // Handle fcmp with constant RHS.
4293 if (C) {
4294 // TODO: If we always required a context function, we wouldn't need to
4295 // special case nans.
4296 if (C->isNaN())
4297 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4298
4299 // TODO: Need version fcmpToClassTest which returns implied class when the
4300 // compare isn't a complete class test. e.g. > 1.0 implies fcPositive, but
4301 // isn't implementable as a class call.
4302 if (C->isNegative() && !C->isNegZero()) {
4304
4305 // TODO: We can catch more cases by using a range check rather than
4306 // relying on CannotBeOrderedLessThanZero.
4307 switch (Pred) {
4308 case FCmpInst::FCMP_UGE:
4309 case FCmpInst::FCMP_UGT:
4310 case FCmpInst::FCMP_UNE: {
4311 KnownFPClass KnownClass = computeLHSClass(Interested);
4312
4313 // (X >= 0) implies (X > C) when (C < 0)
4314 if (KnownClass.cannotBeOrderedLessThanZero())
4315 return getTrue(RetTy);
4316 break;
4317 }
4318 case FCmpInst::FCMP_OEQ:
4319 case FCmpInst::FCMP_OLE:
4320 case FCmpInst::FCMP_OLT: {
4321 KnownFPClass KnownClass = computeLHSClass(Interested);
4322
4323 // (X >= 0) implies !(X < C) when (C < 0)
4324 if (KnownClass.cannotBeOrderedLessThanZero())
4325 return getFalse(RetTy);
4326 break;
4327 }
4328 default:
4329 break;
4330 }
4331 }
4332 // Check FCmp of [min/maxnum or min/maximumnum with const] with other const.
4333 const APFloat *C2;
4334 bool IsMax = match(LHS, m_FMaxNum_or_FMaximumNum(m_Value(), m_APFloat(C2)));
4335 bool IsMin = match(LHS, m_FMinNum_or_FMinimumNum(m_Value(), m_APFloat(C2)));
4336 if ((IsMax && *C2 > *C) || (IsMin && *C2 < *C)) {
4337 // The ordered relationship and min/maxnum or min/maximumnum guarantee
4338 // that we do not have NaN constants, so ordered/unordered preds are
4339 // handled the same.
4340 // FIXME: minnum/maxnum may return a NaN for an sNaN operand, so these
4341 // folds may be inconsistent with other uses of the minnum/maxnum.
4342 switch (Pred) {
4343 case FCmpInst::FCMP_OEQ:
4344 case FCmpInst::FCMP_UEQ:
4345 // minnum(X, LesserC) == C --> false
4346 // maxnum(X, GreaterC) == C --> false
4347 return getFalse(RetTy);
4348 case FCmpInst::FCMP_ONE:
4349 case FCmpInst::FCMP_UNE:
4350 // minnum(X, LesserC) != C --> true
4351 // maxnum(X, GreaterC) != C --> true
4352 return getTrue(RetTy);
4353 case FCmpInst::FCMP_OGE:
4354 case FCmpInst::FCMP_UGE:
4355 case FCmpInst::FCMP_OGT:
4356 case FCmpInst::FCMP_UGT:
4357 // minnum(X, LesserC) >= C --> false
4358 // minnum(X, LesserC) > C --> false
4359 // maxnum(X, GreaterC) >= C --> true
4360 // maxnum(X, GreaterC) > C --> true
4361 return ConstantInt::get(RetTy, IsMax);
4362 case FCmpInst::FCMP_OLE:
4363 case FCmpInst::FCMP_ULE:
4364 case FCmpInst::FCMP_OLT:
4365 case FCmpInst::FCMP_ULT:
4366 // minnum(X, LesserC) <= C --> true
4367 // minnum(X, LesserC) < C --> true
4368 // maxnum(X, GreaterC) <= C --> false
4369 // maxnum(X, GreaterC) < C --> false
4370 return ConstantInt::get(RetTy, !IsMax);
4371 case FCmpInst::FCMP_ORD:
4372 case FCmpInst::FCMP_UNO:
4373 // Reachable because minnum/maxnum may return a NaN for an sNaN operand.
4374 break;
4375 default:
4376 // TRUE/FALSE should be handled before this.
4377 llvm_unreachable("Unexpected fcmp predicate");
4378 }
4379 }
4380 }
4381
4382 // TODO: Could fold this with above if there were a matcher which returned all
4383 // classes in a non-splat vector.
4384 if (match(RHS, m_AnyZeroFP())) {
4385 switch (Pred) {
4386 case FCmpInst::FCMP_OGE:
4387 case FCmpInst::FCMP_ULT: {
4389 if (!FMF.noNaNs())
4390 Interested |= fcNan;
4391
4392 KnownFPClass Known = computeLHSClass(Interested);
4393
4394 // Positive or zero X >= 0.0 --> true
4395 // Positive or zero X < 0.0 --> false
4396 if ((FMF.noNaNs() || Known.isKnownNeverNaN()) &&
4397 Known.cannotBeOrderedLessThanZero())
4398 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4399 break;
4400 }
4401 case FCmpInst::FCMP_UGE:
4402 case FCmpInst::FCMP_OLT: {
4404 KnownFPClass Known = computeLHSClass(Interested);
4405
4406 // Positive or zero or nan X >= 0.0 --> true
4407 // Positive or zero or nan X < 0.0 --> false
4408 if (Known.cannotBeOrderedLessThanZero())
4409 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4410 break;
4411 }
4412 default:
4413 break;
4414 }
4415 }
4416
4417 // If the comparison is with the result of a select instruction, check whether
4418 // comparing with either branch of the select always yields the same value.
4420 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4421 return V;
4422
4423 // If the comparison is with the result of a phi instruction, check whether
4424 // doing the compare with each incoming phi value yields a common result.
4426 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4427 return V;
4428
4429 return nullptr;
4430}
4431
4433 FastMathFlags FMF, const SimplifyQuery &Q) {
4434 return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4435}
4436
4438 ArrayRef<std::pair<Value *, Value *>> Ops,
4439 const SimplifyQuery &Q,
4440 bool AllowRefinement,
4442 unsigned MaxRecurse) {
4443 assert((AllowRefinement || !Q.CanUseUndef) &&
4444 "If AllowRefinement=false then CanUseUndef=false");
4445 for (const auto &OpAndRepOp : Ops) {
4446 // We cannot replace a constant, and shouldn't even try.
4447 if (isa<Constant>(OpAndRepOp.first))
4448 return nullptr;
4449
4450 // Trivial replacement.
4451 if (V == OpAndRepOp.first)
4452 return OpAndRepOp.second;
4453 }
4454
4455 if (!MaxRecurse--)
4456 return nullptr;
4457
4458 auto *I = dyn_cast<Instruction>(V);
4459 if (!I)
4460 return nullptr;
4461
4462 // The arguments of a phi node might refer to a value from a previous
4463 // cycle iteration.
4464 if (isa<PHINode>(I))
4465 return nullptr;
4466
4467 // Don't fold away llvm.is.constant checks based on assumptions.
4469 return nullptr;
4470
4471 // Don't simplify freeze.
4472 if (isa<FreezeInst>(I))
4473 return nullptr;
4474
4475 for (const auto &OpAndRepOp : Ops) {
4476 // For vector types, the simplification must hold per-lane, so forbid
4477 // potentially cross-lane operations like shufflevector.
4478 if (OpAndRepOp.first->getType()->isVectorTy() &&
4480 return nullptr;
4481 }
4482
4483 // Replace Op with RepOp in instruction operands.
4485 bool AnyReplaced = false;
4486 for (Use &InstOp : I->operands()) {
4487 // A select with a constant condition will not use one of its value
4488 // operands. Don't simplify it to avoid unnecessary flag drops.
4489 if (isa<SelectInst>(I) && InstOp.getOperandNo() != 0) {
4490 auto *Cond = dyn_cast<ConstantInt>(NewOps[0]);
4491 if (Cond && InstOp.getOperandNo() == 1 + Cond->isOne()) {
4492 NewOps.push_back(PoisonValue::get(I->getType()));
4493 continue;
4494 }
4495 }
4496
4497 if (Value *NewInstOp = simplifyWithOpsReplaced(
4498 InstOp, Ops, Q, AllowRefinement, DropFlags, MaxRecurse)) {
4499 NewOps.push_back(NewInstOp);
4500 AnyReplaced = InstOp != NewInstOp;
4501 } else {
4502 NewOps.push_back(InstOp);
4503 }
4504
4505 // Bail out if any operand is undef and SimplifyQuery disables undef
4506 // simplification. Constant folding currently doesn't respect this option.
4507 if (isa<UndefValue>(NewOps.back()) && !Q.CanUseUndef)
4508 return nullptr;
4509 }
4510
4511 if (!AnyReplaced)
4512 return nullptr;
4513
4514 if (!AllowRefinement) {
4515 // General InstSimplify functions may refine the result, e.g. by returning
4516 // a constant for a potentially poison value. To avoid this, implement only
4517 // a few non-refining but profitable transforms here.
4518
4519 // Replacement values are non-poison by assumption.
4520 auto IsAssumedNonPoison = [&](Value *V) {
4521 return any_of(Ops, [=](const auto &Rep) { return Rep.second == V; });
4522 };
4523
4524 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4525 unsigned Opcode = BO->getOpcode();
4526 // id op x -> x, x op id -> x
4527 // Exclude floats, because x op id may produce a different NaN value.
4528 if (!BO->getType()->isFPOrFPVectorTy()) {
4529 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4530 return NewOps[1];
4531 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4532 /* RHS */ true))
4533 return NewOps[0];
4534 }
4535
4536 // x & x -> x, x | x -> x
4537 if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4538 NewOps[0] == NewOps[1]) {
4539 // or disjoint x, x results in poison.
4540 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BO)) {
4541 if (PDI->isDisjoint()) {
4542 if (!DropFlags)
4543 return nullptr;
4544 DropFlags->push_back(BO);
4545 }
4546 }
4547 return NewOps[0];
4548 }
4549
4550 // x - x -> 0, x ^ x -> 0. This is non-refining, because x is non-poison
4551 // by assumption and this case never wraps, so nowrap flags can be
4552 // ignored.
4553 if ((Opcode == Instruction::Sub || Opcode == Instruction::Xor) &&
4554 NewOps[0] == NewOps[1] && IsAssumedNonPoison(NewOps[0]))
4555 return Constant::getNullValue(I->getType());
4556
4557 // If we are substituting an absorber constant into a binop and extra
4558 // poison can't leak if we remove the select -- because both operands of
4559 // the binop are based on the same value -- then it may be safe to replace
4560 // the value with the absorber constant. Examples:
4561 // (Op == 0) ? 0 : (Op & -Op) --> Op & -Op
4562 // (Op == 0) ? 0 : (Op * (binop Op, C)) --> Op * (binop Op, C)
4563 // (Op == -1) ? -1 : (Op | (binop C, Op) --> Op | (binop C, Op)
4564 Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, I->getType());
4565 if ((NewOps[0] == Absorber || NewOps[1] == Absorber) &&
4566 any_of(Ops,
4567 [=](const auto &Rep) { return impliesPoison(BO, Rep.first); }))
4568 return Absorber;
4569 }
4570
4571 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4572 auto WithFlagsDropped = [&](Value *Res) -> Value * {
4573 if (II->hasPoisonGeneratingAnnotations()) {
4574 if (!DropFlags)
4575 return nullptr;
4576
4577 DropFlags->push_back(II);
4578 }
4579 return Res;
4580 };
4581
4582 // `x == y ? 0 : ucmp(x, y)` where under the replacement y -> x,
4583 // `ucmp(x, x)` becomes `0`.
4584 if ((II->getIntrinsicID() == Intrinsic::scmp ||
4585 II->getIntrinsicID() == Intrinsic::ucmp) &&
4586 NewOps[0] == NewOps[1] && IsAssumedNonPoison(NewOps[0]))
4587 return WithFlagsDropped(ConstantInt::get(I->getType(), 0));
4588
4589 if (auto *MMI = dyn_cast<MinMaxIntrinsic>(II)) {
4590 const APInt Identity = MMI->getIdentity();
4591
4592 if (match(NewOps[0], m_SpecificInt(Identity)))
4593 return WithFlagsDropped(NewOps[1]);
4594 if (match(NewOps[1], m_SpecificInt(Identity)))
4595 return WithFlagsDropped(NewOps[0]);
4596 if (NewOps[0] == NewOps[1])
4597 return WithFlagsDropped(NewOps[0]);
4598 }
4599 }
4600
4602 // getelementptr x, 0 -> x.
4603 // This never returns poison, even if inbounds is set.
4604 if (NewOps.size() == 2 && match(NewOps[1], m_Zero()))
4605 return NewOps[0];
4606 }
4607 } else {
4608 // The simplification queries below may return the original value. Consider:
4609 // %div = udiv i32 %arg, %arg2
4610 // %mul = mul nsw i32 %div, %arg2
4611 // %cmp = icmp eq i32 %mul, %arg
4612 // %sel = select i1 %cmp, i32 %div, i32 undef
4613 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4614 // simplifies back to %arg. This can only happen because %mul does not
4615 // dominate %div. To ensure a consistent return value contract, we make sure
4616 // that this case returns nullptr as well.
4617 auto PreventSelfSimplify = [V](Value *Simplified) {
4618 return Simplified != V ? Simplified : nullptr;
4619 };
4620
4621 return PreventSelfSimplify(::simplifyInstructionWithOperands(
4622 I, NewOps, Q, /*DropAnnotations=*/nullptr, MaxRecurse));
4623 }
4624
4625 // If all operands are constant after substituting Op for RepOp then we can
4626 // constant fold the instruction.
4628 for (Value *NewOp : NewOps) {
4629 if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4630 ConstOps.push_back(ConstOp);
4631 else
4632 return nullptr;
4633 }
4634
4635 // Consider:
4636 // %cmp = icmp eq i32 %x, 2147483647
4637 // %add = add nsw i32 %x, 1
4638 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
4639 //
4640 // We can't replace %sel with %add unless we strip away the flags (which
4641 // will be done in InstCombine).
4642 // TODO: This may be unsound, because it only catches some forms of
4643 // refinement.
4644 if (!AllowRefinement) {
4645 auto *II = dyn_cast<IntrinsicInst>(I);
4646
4647 auto CanNotCreatePoisonSpecialCases = [&]() {
4648 // abs cannot create poison if the value is known to never be int_min,
4649 // and it has no poison-generating attributes.
4650 if (II && II->getIntrinsicID() == Intrinsic::abs &&
4651 ConstOps[0]->isNotMinSignedValue() &&
4652 !II->hasPoisonGeneratingAttributes() &&
4653 !II->hasPoisonGeneratingMetadata())
4654 return true;
4655
4656 if (auto *Cmp = dyn_cast<ICmpInst>(I)) {
4657 // icmp can only create poison via samesign with different signs.
4658 const APInt *C1, *C2;
4659 return !Cmp->hasSameSign() ||
4660 (match(ConstOps[0], m_APInt(C1)) &&
4661 match(ConstOps[1], m_APInt(C2)) &&
4662 C1->isNonNegative() == C2->isNonNegative());
4663 }
4664 return false;
4665 };
4666 if (CanNotCreatePoisonSpecialCases())
4667 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI,
4668 /*AllowNonDeterministic=*/false);
4669
4670 if (canCreatePoison(cast<Operator>(I), !DropFlags))
4671 return nullptr;
4672
4673 if (DropFlags && II) {
4674 // If we're going to change the poison flag of abs/ctz to false, also
4675 // perform constant folding that way, so we get an integer instead of a
4676 // poison value here.
4677 switch (II->getIntrinsicID()) {
4678 case Intrinsic::abs:
4679 case Intrinsic::ctlz:
4680 case Intrinsic::cttz:
4681 ConstOps[1] = ConstantInt::getFalse(I->getContext());
4682 break;
4683 default:
4684 break;
4685 }
4686 }
4687
4688 Constant *Res = ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI,
4689 /*AllowNonDeterministic=*/false);
4690 if (DropFlags && Res && I->hasPoisonGeneratingAnnotations())
4691 DropFlags->push_back(I);
4692 return Res;
4693 }
4694
4695 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI,
4696 /*AllowNonDeterministic=*/false);
4697}
4698
4700 const SimplifyQuery &Q,
4701 bool AllowRefinement,
4703 unsigned MaxRecurse) {
4704 return simplifyWithOpsReplaced(V, {{Op, RepOp}}, Q, AllowRefinement,
4705 DropFlags, MaxRecurse);
4706}
4707
4709 const SimplifyQuery &Q,
4710 bool AllowRefinement,
4711 SmallVectorImpl<Instruction *> *DropFlags) {
4712 // If refinement is disabled, also disable undef simplifications (which are
4713 // always refinements) in SimplifyQuery.
4714 if (!AllowRefinement)
4715 return ::simplifyWithOpReplaced(V, Op, RepOp, Q.getWithoutUndef(),
4716 AllowRefinement, DropFlags, RecursionLimit);
4717 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, DropFlags,
4719}
4720
4721/// Try to simplify a select instruction when its condition operand is an
4722/// integer comparison where one operand of the compare is a constant.
4723static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4724 const APInt *Y, bool TrueWhenUnset) {
4725 const APInt *C;
4726
4727 // (X & Y) == 0 ? X & ~Y : X --> X
4728 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
4729 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4730 *Y == ~*C)
4731 return TrueWhenUnset ? FalseVal : TrueVal;
4732
4733 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
4734 // (X & Y) != 0 ? X : X & ~Y --> X
4735 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4736 *Y == ~*C)
4737 return TrueWhenUnset ? FalseVal : TrueVal;
4738
4739 if (Y->isPowerOf2()) {
4740 // (X & Y) == 0 ? X | Y : X --> X | Y
4741 // (X & Y) != 0 ? X | Y : X --> X
4742 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4743 *Y == *C) {
4744 // We can't return the or if it has the disjoint flag.
4745 if (TrueWhenUnset && cast<PossiblyDisjointInst>(TrueVal)->isDisjoint())
4746 return nullptr;
4747 return TrueWhenUnset ? TrueVal : FalseVal;
4748 }
4749
4750 // (X & Y) == 0 ? X : X | Y --> X
4751 // (X & Y) != 0 ? X : X | Y --> X | Y
4752 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4753 *Y == *C) {
4754 // We can't return the or if it has the disjoint flag.
4755 if (!TrueWhenUnset && cast<PossiblyDisjointInst>(FalseVal)->isDisjoint())
4756 return nullptr;
4757 return TrueWhenUnset ? TrueVal : FalseVal;
4758 }
4759 }
4760
4761 return nullptr;
4762}
4763
4764static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4765 CmpPredicate Pred, Value *TVal,
4766 Value *FVal) {
4767 // Canonicalize common cmp+sel operand as CmpLHS.
4768 if (CmpRHS == TVal || CmpRHS == FVal) {
4769 std::swap(CmpLHS, CmpRHS);
4771 }
4772
4773 // Canonicalize common cmp+sel operand as TVal.
4774 if (CmpLHS == FVal) {
4775 std::swap(TVal, FVal);
4777 }
4778
4779 // A vector select may be shuffling together elements that are equivalent
4780 // based on the max/min/select relationship.
4781 Value *X = CmpLHS, *Y = CmpRHS;
4782 bool PeekedThroughSelectShuffle = false;
4783 auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
4784 if (Shuf && Shuf->isSelect()) {
4785 if (Shuf->getOperand(0) == Y)
4786 FVal = Shuf->getOperand(1);
4787 else if (Shuf->getOperand(1) == Y)
4788 FVal = Shuf->getOperand(0);
4789 else
4790 return nullptr;
4791 PeekedThroughSelectShuffle = true;
4792 }
4793
4794 // (X pred Y) ? X : max/min(X, Y)
4795 auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
4796 if (!MMI || TVal != X ||
4798 return nullptr;
4799
4800 // (X > Y) ? X : max(X, Y) --> max(X, Y)
4801 // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4802 // (X < Y) ? X : min(X, Y) --> min(X, Y)
4803 // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4804 //
4805 // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4806 // (X > Y) ? X : (Z ? max(X, Y) : Y)
4807 // If Z is true, this reduces as above, and if Z is false:
4808 // (X > Y) ? X : Y --> max(X, Y)
4809 ICmpInst::Predicate MMPred = MMI->getPredicate();
4810 if (MMPred == CmpInst::getStrictPredicate(Pred))
4811 return MMI;
4812
4813 // Other transforms are not valid with a shuffle.
4814 if (PeekedThroughSelectShuffle)
4815 return nullptr;
4816
4817 // (X < Y) ? X : max(X, Y) --> X
4818 // (X <= Y) ? X : max(X, Y) --> X
4819 // (X > Y) ? X : min(X, Y) --> X
4820 // (X >= Y) ? X : min(X, Y) --> X
4822 if (MMPred == CmpInst::getStrictPredicate(InvPred))
4823 return X;
4824
4825 return nullptr;
4826}
4827
4828/// An alternative way to test if a bit is set or not.
4829/// uses e.g. sgt/slt or trunc instead of eq/ne.
4830static Value *simplifySelectWithBitTest(Value *CondVal, Value *TrueVal,
4831 Value *FalseVal) {
4832 if (auto Res = decomposeBitTest(CondVal))
4833 return simplifySelectBitTest(TrueVal, FalseVal, Res->X, &Res->Mask,
4834 Res->Pred == ICmpInst::ICMP_EQ);
4835
4836 return nullptr;
4837}
4838
4839/// Try to simplify a select instruction when its condition operand is an
4840/// integer equality or floating-point equivalence comparison.
4842 ArrayRef<std::pair<Value *, Value *>> Replacements, Value *TrueVal,
4843 Value *FalseVal, const SimplifyQuery &Q,
4844 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned MaxRecurse) {
4845 unsigned OrigDropAnnotationsSize =
4846 DropAnnotations ? DropAnnotations->size() : 0;
4847 Value *SimplifiedFalseVal = simplifyWithOpsReplaced(
4848 FalseVal, Replacements, Q.getWithoutUndef(),
4849 /*AllowRefinement=*/false, DropAnnotations, MaxRecurse);
4850 if (!SimplifiedFalseVal)
4851 SimplifiedFalseVal = FalseVal;
4852
4853 Value *SimplifiedTrueVal = simplifyWithOpsReplaced(
4854 TrueVal, Replacements, Q,
4855 /*AllowRefinement=*/true, /*DropFlags=*/nullptr, MaxRecurse);
4856 if (!SimplifiedTrueVal)
4857 SimplifiedTrueVal = TrueVal;
4858
4859 if (SimplifiedFalseVal == SimplifiedTrueVal)
4860 return FalseVal;
4861
4862 // Don't drop annotations if we did not fold.
4863 if (DropAnnotations)
4864 DropAnnotations->truncate(OrigDropAnnotationsSize);
4865 return nullptr;
4866}
4867
4868/// Try to simplify a select instruction when its condition operand is an
4869/// integer comparison.
4871 Value *CondVal, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q,
4872 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned MaxRecurse) {
4874 Value *CmpLHS, *CmpRHS;
4875 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4876 return nullptr;
4877
4878 if (Value *V =
4879 simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4880 return V;
4881
4882 // Canonicalize ne to eq predicate.
4883 if (Pred == ICmpInst::ICMP_NE) {
4885 std::swap(TrueVal, FalseVal);
4886 }
4887
4888 // Check for integer min/max with a limit constant:
4889 // X > MIN_INT ? X : MIN_INT --> X
4890 // X < MAX_INT ? X : MAX_INT --> X
4891 if (TrueVal->getType()->isIntOrIntVectorTy()) {
4892 Value *X, *Y;
4894 matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4895 X, Y)
4896 .Flavor;
4899 X->getType()->getScalarSizeInBits());
4900 if (match(Y, m_SpecificInt(LimitC)))
4901 return X;
4902 }
4903 }
4904
4905 if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4906 Value *X;
4907 const APInt *Y;
4908 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4909 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4910 /*TrueWhenUnset=*/true))
4911 return V;
4912
4913 // Test for a zero-shift-guard-op around rotates. These are used to
4914 // avoid UB from oversized shifts in raw IR rotate patterns, but the
4915 // intrinsics do not have that problem.
4916 // We do not allow this transform for the general funnel shift case because
4917 // that would not preserve the poison safety of the original code.
4918 Value *ShAmt;
4919 auto isRotate =
4921 m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4922 if (match(FalseVal, isRotate) && TrueVal == X) {
4923 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4924 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4925 if (CmpLHS == ShAmt)
4926 return FalseVal;
4927 // Compute the bitwidth of the value being rotated.
4928 unsigned BW = X->getType()->getScalarSizeInBits();
4929 // Handle the cases where the expression to be checked for zero is not the
4930 // shift amount but the `shAmt % bitwidth` which is equivalent to `shAmt &
4931 // (bitwidth - 1)` provided the bitwidth is a power of 2.
4932 //
4933 // ((ShAmt & (BW-1)) == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4934 // ((ShAmt & (BW-1)) == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4935 if (isPowerOf2_32(BW) &&
4936 match(CmpLHS, m_c_And(m_Specific(ShAmt), m_SpecificInt(BW - 1))))
4937 return FalseVal;
4938 // (ShAmt % BW == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4939 // (ShAmt % BW == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4940 if (match(CmpLHS, m_URem(m_Specific(ShAmt), m_SpecificInt(BW))))
4941 return FalseVal;
4942 }
4943 }
4944
4945 // If we have a scalar equality comparison, then we know the value in one of
4946 // the arms of the select. See if substituting this value into the arm and
4947 // simplifying the result yields the same value as the other arm.
4948 if (Pred == ICmpInst::ICMP_EQ) {
4949 if (CmpLHS->getType()->isIntOrIntVectorTy() ||
4950 canReplacePointersIfEqual(CmpLHS, CmpRHS, Q.DL))
4951 if (Value *V = simplifySelectWithEquivalence({{CmpLHS, CmpRHS}}, TrueVal,
4952 FalseVal, Q, DropAnnotations,
4953 MaxRecurse))
4954 return V;
4955 if (CmpLHS->getType()->isIntOrIntVectorTy() ||
4956 canReplacePointersIfEqual(CmpRHS, CmpLHS, Q.DL))
4957 if (Value *V = simplifySelectWithEquivalence({{CmpRHS, CmpLHS}}, TrueVal,
4958 FalseVal, Q, DropAnnotations,
4959 MaxRecurse))
4960 return V;
4961
4962 Value *X;
4963 Value *Y;
4964 // select((X | Y) == 0 ? X : 0) --> 0 (commuted 2 ways)
4965 if (match(CmpLHS, m_Or(m_Value(X), m_Value(Y))) &&
4966 match(CmpRHS, m_Zero())) {
4967 // (X | Y) == 0 implies X == 0 and Y == 0.
4968 if (Value *V = simplifySelectWithEquivalence({{X, CmpRHS}, {Y, CmpRHS}},
4969 TrueVal, FalseVal, Q,
4970 DropAnnotations, MaxRecurse))
4971 return V;
4972 }
4973
4974 // select((X & Y) == -1 ? X : -1) --> -1 (commuted 2 ways)
4975 if (match(CmpLHS, m_And(m_Value(X), m_Value(Y))) &&
4976 match(CmpRHS, m_AllOnes())) {
4977 // (X & Y) == -1 implies X == -1 and Y == -1.
4978 if (Value *V = simplifySelectWithEquivalence({{X, CmpRHS}, {Y, CmpRHS}},
4979 TrueVal, FalseVal, Q,
4980 DropAnnotations, MaxRecurse))
4981 return V;
4982 }
4983 }
4984
4985 return nullptr;
4986}
4987
4988/// Try to simplify a select instruction when its condition operand is a
4989/// floating-point comparison.
4991 Value *Cond, Value *T, Value *F, FastMathFlags FMF, const SimplifyQuery &Q,
4992 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned MaxRecurse) {
4994 Value *CmpLHS, *CmpRHS;
4995 if (!match(Cond, m_FCmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4996 return nullptr;
4998
4999 bool IsEquiv = I->isEquivalence();
5000 if (I->isEquivalence(/*Invert=*/true)) {
5001 std::swap(T, F);
5003 IsEquiv = true;
5004 }
5005
5006 // This transforms is safe if at least one operand is known to not be zero.
5007 // Otherwise, the select can change the sign of a zero operand.
5008 if (IsEquiv) {
5009 if (Value *V = simplifySelectWithEquivalence({{CmpLHS, CmpRHS}}, T, F, Q,
5010 DropAnnotations, MaxRecurse))
5011 return V;
5012 if (Value *V = simplifySelectWithEquivalence({{CmpRHS, CmpLHS}}, T, F, Q,
5013 DropAnnotations, MaxRecurse))
5014 return V;
5015 }
5016
5017 // Canonicalize CmpLHS to be T, and CmpRHS to be F, if they're swapped.
5018 if (CmpLHS == F && CmpRHS == T)
5019 std::swap(CmpLHS, CmpRHS);
5020
5021 if (CmpLHS != T || CmpRHS != F)
5022 return nullptr;
5023
5024 // This transform is also safe if we do not have (do not care about) -0.0.
5025 if (FMF.noSignedZeros()) {
5026 // (T == F) ? T : F --> F
5027 if (Pred == FCmpInst::FCMP_OEQ)
5028 return F;
5029
5030 // (T != F) ? T : F --> T
5031 if (Pred == FCmpInst::FCMP_UNE)
5032 return T;
5033 }
5034
5035 return nullptr;
5036}
5037
5038/// Look for the following pattern and simplify %to_fold to %identicalPhi.
5039/// Here %phi, %to_fold and %phi.next perform the same functionality as
5040/// %identicalPhi and hence the select instruction %to_fold can be folded
5041/// into %identicalPhi.
5042///
5043/// BB1:
5044/// %identicalPhi = phi [ X, %BB0 ], [ %identicalPhi.next, %BB1 ]
5045/// %phi = phi [ X, %BB0 ], [ %phi.next, %BB1 ]
5046/// ...
5047/// %identicalPhi.next = select %cmp, %val, %identicalPhi
5048/// (or select %cmp, %identicalPhi, %val)
5049/// %to_fold = select %cmp2, %identicalPhi, %phi
5050/// %phi.next = select %cmp, %val, %to_fold
5051/// (or select %cmp, %to_fold, %val)
5052///
5053/// Prove that %phi and %identicalPhi are the same by induction:
5054///
5055/// Base case: Both %phi and %identicalPhi are equal on entry to the loop.
5056/// Inductive case:
5057/// Suppose %phi and %identicalPhi are equal at iteration i.
5058/// We look at their values at iteration i+1 which are %phi.next and
5059/// %identicalPhi.next. They would have become different only when %cmp is
5060/// false and the corresponding values %to_fold and %identicalPhi differ
5061/// (similar reason for the other "or" case in the bracket).
5062///
5063/// The only condition when %to_fold and %identicalPh could differ is when %cmp2
5064/// is false and %to_fold is %phi, which contradicts our inductive hypothesis
5065/// that %phi and %identicalPhi are equal. Thus %phi and %identicalPhi are
5066/// always equal at iteration i+1.
5068 if (PN.getParent() != IdenticalPN.getParent())
5069 return false;
5070 if (PN.getNumIncomingValues() != 2)
5071 return false;
5072
5073 // Check that only the backedge incoming value is different.
5074 unsigned DiffVals = 0;
5075 BasicBlock *DiffValBB = nullptr;
5076 for (unsigned i = 0; i < 2; i++) {
5077 BasicBlock *PredBB = PN.getIncomingBlock(i);
5078 if (PN.getIncomingValue(i) !=
5079 IdenticalPN.getIncomingValueForBlock(PredBB)) {
5080 DiffVals++;
5081 DiffValBB = PredBB;
5082 }
5083 }
5084 if (DiffVals != 1)
5085 return false;
5086 // Now check that the backedge incoming values are two select
5087 // instructions with the same condition. Either their true
5088 // values are the same, or their false values are the same.
5089 auto *SI = dyn_cast<SelectInst>(PN.getIncomingValueForBlock(DiffValBB));
5090 auto *IdenticalSI =
5091 dyn_cast<SelectInst>(IdenticalPN.getIncomingValueForBlock(DiffValBB));
5092 if (!SI || !IdenticalSI)
5093 return false;
5094 if (SI->getCondition() != IdenticalSI->getCondition())
5095 return false;
5096
5097 SelectInst *SIOtherVal = nullptr;
5098 Value *IdenticalSIOtherVal = nullptr;
5099 if (SI->getTrueValue() == IdenticalSI->getTrueValue()) {
5100 SIOtherVal = dyn_cast<SelectInst>(SI->getFalseValue());
5101 IdenticalSIOtherVal = IdenticalSI->getFalseValue();
5102 } else if (SI->getFalseValue() == IdenticalSI->getFalseValue()) {
5103 SIOtherVal = dyn_cast<SelectInst>(SI->getTrueValue());
5104 IdenticalSIOtherVal = IdenticalSI->getTrueValue();
5105 } else {
5106 return false;
5107 }
5108
5109 // Now check that the other values in select, i.e., %to_fold and
5110 // %identicalPhi, are essentially the same value.
5111 if (!SIOtherVal || IdenticalSIOtherVal != &IdenticalPN)
5112 return false;
5113 if (!(SIOtherVal->getTrueValue() == &IdenticalPN &&
5114 SIOtherVal->getFalseValue() == &PN) &&
5115 !(SIOtherVal->getTrueValue() == &PN &&
5116 SIOtherVal->getFalseValue() == &IdenticalPN))
5117 return false;
5118 return true;
5119}
5120
5121/// Given operands for a SelectInst, see if we can fold the result.
5122/// If not, this returns null.
5123static Value *
5125 FastMathFlags FMF, const SimplifyQuery &Q,
5126 SmallVectorImpl<Instruction *> *DropAnnotations,
5127 unsigned MaxRecurse) {
5128 if (auto *CondC = dyn_cast<Constant>(Cond)) {
5129 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
5130 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
5131 if (Constant *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC))
5132 return C;
5133
5134 // select poison, X, Y -> poison
5135 if (isa<PoisonValue>(CondC))
5136 return PoisonValue::get(TrueVal->getType());
5137
5138 // select undef, X, Y -> X or Y
5139 if (Q.isUndefValue(CondC))
5140 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
5141
5142 // select true, X, Y --> X
5143 // select false, X, Y --> Y
5144 // For vectors, allow undef/poison elements in the condition to match the
5145 // defined elements, so we can eliminate the select.
5146 if (match(CondC, m_One()))
5147 return TrueVal;
5148 if (match(CondC, m_Zero()))
5149 return FalseVal;
5150 }
5151
5152 assert(Cond->getType()->isIntOrIntVectorTy(1) &&
5153 "Select must have bool or bool vector condition");
5154 assert(TrueVal->getType() == FalseVal->getType() &&
5155 "Select must have same types for true/false ops");
5156
5157 if (Cond->getType() == TrueVal->getType()) {
5158 // select i1 Cond, i1 true, i1 false --> i1 Cond
5159 if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
5160 return Cond;
5161
5162 // (X && Y) ? X : Y --> Y (commuted 2 ways)
5163 if (match(Cond, m_c_LogicalAnd(m_Specific(TrueVal), m_Specific(FalseVal))))
5164 return FalseVal;
5165
5166 // (X || Y) ? X : Y --> X (commuted 2 ways)
5167 if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Specific(FalseVal))))
5168 return TrueVal;
5169
5170 // (X || Y) ? false : X --> false (commuted 2 ways)
5171 if (match(Cond, m_c_LogicalOr(m_Specific(FalseVal), m_Value())) &&
5172 match(TrueVal, m_ZeroInt()))
5173 return ConstantInt::getFalse(Cond->getType());
5174
5175 // Match patterns that end in logical-and.
5176 if (match(FalseVal, m_ZeroInt())) {
5177 // !(X || Y) && X --> false (commuted 2 ways)
5178 if (match(Cond, m_Not(m_c_LogicalOr(m_Specific(TrueVal), m_Value()))))
5179 return ConstantInt::getFalse(Cond->getType());
5180 // X && !(X || Y) --> false (commuted 2 ways)
5181 if (match(TrueVal, m_Not(m_c_LogicalOr(m_Specific(Cond), m_Value()))))
5182 return ConstantInt::getFalse(Cond->getType());
5183
5184 // (X || Y) && Y --> Y (commuted 2 ways)
5185 if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Value())))
5186 return TrueVal;
5187 // Y && (X || Y) --> Y (commuted 2 ways)
5188 if (match(TrueVal, m_c_LogicalOr(m_Specific(Cond), m_Value())))
5189 return Cond;
5190
5191 // (X || Y) && (X || !Y) --> X (commuted 8 ways)
5192 Value *X, *Y;
5195 return X;
5196 if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
5198 return X;
5199 }
5200
5201 // Match patterns that end in logical-or.
5202 if (match(TrueVal, m_One())) {
5203 // !(X && Y) || X --> true (commuted 2 ways)
5204 if (match(Cond, m_Not(m_c_LogicalAnd(m_Specific(FalseVal), m_Value()))))
5205 return ConstantInt::getTrue(Cond->getType());
5206 // X || !(X && Y) --> true (commuted 2 ways)
5207 if (match(FalseVal, m_Not(m_c_LogicalAnd(m_Specific(Cond), m_Value()))))
5208 return ConstantInt::getTrue(Cond->getType());
5209
5210 // (X && Y) || Y --> Y (commuted 2 ways)
5211 if (match(Cond, m_c_LogicalAnd(m_Specific(FalseVal), m_Value())))
5212 return FalseVal;
5213 // Y || (X && Y) --> Y (commuted 2 ways)
5214 if (match(FalseVal, m_c_LogicalAnd(m_Specific(Cond), m_Value())))
5215 return Cond;
5216 }
5217 }
5218
5219 // select ?, X, X -> X
5220 if (TrueVal == FalseVal)
5221 return TrueVal;
5222
5223 if (Cond == TrueVal) {
5224 // select i1 X, i1 X, i1 false --> X (logical-and)
5225 if (match(FalseVal, m_ZeroInt()))
5226 return Cond;
5227 // select i1 X, i1 X, i1 true --> true
5228 if (match(FalseVal, m_One()))
5229 return ConstantInt::getTrue(Cond->getType());
5230 }
5231 if (Cond == FalseVal) {
5232 // select i1 X, i1 true, i1 X --> X (logical-or)
5233 if (match(TrueVal, m_One()))
5234 return Cond;
5235 // select i1 X, i1 false, i1 X --> false
5236 if (match(TrueVal, m_ZeroInt()))
5237 return ConstantInt::getFalse(Cond->getType());
5238 }
5239
5240 // If the true or false value is poison, we can fold to the other value.
5241 // If the true or false value is undef, we can fold to the other value as
5242 // long as the other value isn't poison.
5243 // select ?, poison, X -> X
5244 // select ?, undef, X -> X
5245 if (isa<PoisonValue>(TrueVal) ||
5246 (Q.isUndefValue(TrueVal) && impliesPoison(FalseVal, Cond)))
5247 return FalseVal;
5248 // select ?, X, poison -> X
5249 // select ?, X, undef -> X
5250 if (isa<PoisonValue>(FalseVal) ||
5251 (Q.isUndefValue(FalseVal) && impliesPoison(TrueVal, Cond)))
5252 return TrueVal;
5253
5254 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
5255 Constant *TrueC, *FalseC;
5256 if (isa<FixedVectorType>(TrueVal->getType()) &&
5257 match(TrueVal, m_Constant(TrueC)) &&
5258 match(FalseVal, m_Constant(FalseC))) {
5259 unsigned NumElts =
5260 cast<FixedVectorType>(TrueC->getType())->getNumElements();
5262 for (unsigned i = 0; i != NumElts; ++i) {
5263 // Bail out on incomplete vector constants.
5264 Constant *TEltC = TrueC->getAggregateElement(i);
5265 Constant *FEltC = FalseC->getAggregateElement(i);
5266 if (!TEltC || !FEltC)
5267 break;
5268
5269 // If the elements match (undef or not), that value is the result. If only
5270 // one element is undef, choose the defined element as the safe result.
5271 if (TEltC == FEltC)
5272 NewC.push_back(TEltC);
5273 else if (isa<PoisonValue>(TEltC) ||
5274 (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
5275 NewC.push_back(FEltC);
5276 else if (isa<PoisonValue>(FEltC) ||
5277 (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
5278 NewC.push_back(TEltC);
5279 else
5280 break;
5281 }
5282 if (NewC.size() == NumElts)
5283 return ConstantVector::get(NewC);
5284 }
5285
5286 if (Value *V = simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q,
5287 DropAnnotations, MaxRecurse))
5288 return V;
5289
5290 if (Value *V = simplifySelectWithBitTest(Cond, TrueVal, FalseVal))
5291 return V;
5292
5293 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, FMF, Q,
5294 DropAnnotations, MaxRecurse))
5295 return V;
5296
5297 std::optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CtxI, Q.DL);
5298 if (Imp)
5299 return *Imp ? TrueVal : FalseVal;
5300 // Look for same PHIs in the true and false values.
5301 if (auto *TruePHI = dyn_cast<PHINode>(TrueVal))
5302 if (auto *FalsePHI = dyn_cast<PHINode>(FalseVal)) {
5303 if (isSelectWithIdenticalPHI(*TruePHI, *FalsePHI))
5304 return FalseVal;
5305 if (isSelectWithIdenticalPHI(*FalsePHI, *TruePHI))
5306 return TrueVal;
5307 }
5308 return nullptr;
5309}
5310
5311Value *
5313 FastMathFlags FMF, const SimplifyQuery &Q,
5314 SmallVectorImpl<Instruction *> *DropAnnotations) {
5315 return ::simplifySelectInst(Cond, TrueVal, FalseVal, FMF, Q, DropAnnotations,
5317}
5318
5319/// Given operands for an GetElementPtrInst, see if we can fold the result.
5320/// If not, this returns null.
5321static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
5323 const SimplifyQuery &Q, unsigned) {
5324 // The type of the GEP pointer operand.
5325 unsigned AS =
5326 cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
5327
5328 // getelementptr P -> P.
5329 if (Indices.empty())
5330 return Ptr;
5331
5332 // Compute the (pointer) type returned by the GEP instruction.
5333 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
5334 Type *GEPTy = Ptr->getType();
5335 if (!GEPTy->isVectorTy()) {
5336 for (Value *Op : Indices) {
5337 // If one of the operands is a vector, the result type is a vector of
5338 // pointers. All vector operands must have the same number of elements.
5339 if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
5340 GEPTy = VectorType::get(GEPTy, VT->getElementCount());
5341 break;
5342 }
5343 }
5344 }
5345
5346 // All-zero GEP is a no-op, unless it performs a vector splat.
5347 if (Ptr->getType() == GEPTy && all_of(Indices, match_fn(m_Zero())))
5348 return Ptr;
5349
5350 // getelementptr poison, idx -> poison
5351 // getelementptr baseptr, poison -> poison
5352 if (isa<PoisonValue>(Ptr) || any_of(Indices, IsaPred<PoisonValue>))
5353 return PoisonValue::get(GEPTy);
5354
5355 // getelementptr undef, idx -> undef
5356 if (Q.isUndefValue(Ptr))
5357 return UndefValue::get(GEPTy);
5358
5359 bool IsScalableVec =
5360 SrcTy->isScalableTy() || any_of(Indices, [](const Value *V) {
5361 return isa<ScalableVectorType>(V->getType());
5362 });
5363
5364 if (Indices.size() == 1) {
5365 Type *Ty = SrcTy;
5366 if (!IsScalableVec && Ty->isSized()) {
5367 Value *P;
5368 uint64_t C;
5369 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
5370 // getelementptr P, N -> P if P points to a type of zero size.
5371 if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
5372 return Ptr;
5373
5374 // The following transforms are only safe if the ptrtoint cast
5375 // doesn't truncate the address of the pointers. The non-address bits
5376 // must be the same, as the underlying objects are the same.
5377 if (Indices[0]->getType()->getScalarSizeInBits() >=
5378 Q.DL.getAddressSizeInBits(AS)) {
5379 auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
5380 return P->getType() == GEPTy &&
5382 };
5383 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
5384 if (TyAllocSize == 1 &&
5385 match(Indices[0], m_Sub(m_PtrToIntOrAddr(m_Value(P)),
5386 m_PtrToIntOrAddr(m_Specific(Ptr)))) &&
5387 CanSimplify())
5388 return P;
5389
5390 // getelementptr V, (ashr exact (sub P, V), C) -> P if P points to a
5391 // type of size 1 << C.
5392 if (match(Indices[0],
5395 m_ConstantInt(C)))) &&
5396 TyAllocSize == 1ULL << C && CanSimplify())
5397 return P;
5398
5399 // getelementptr V, (sdiv exact (sub P, V), C) -> P if P points to a
5400 // type of size C.
5401 if (match(Indices[0],
5404 m_SpecificInt(TyAllocSize)))) &&
5405 CanSimplify())
5406 return P;
5407 }
5408 }
5409 }
5410
5411 // Match the index before stripping the base below, which is more expensive.
5412 Value *PtrOp;
5413 bool IsNeg = match(Indices.back(), m_Neg(m_PtrToInt(m_Value(PtrOp))));
5414 if ((IsNeg || match(Indices.back(), m_Not(m_PtrToInt(m_Value(PtrOp))))) &&
5415 !IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
5416 all_of(Indices.drop_back(1), match_fn(m_Zero()))) {
5417 unsigned IdxWidth =
5419 if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
5420 APInt BasePtrOffset(IdxWidth, 0);
5421 Value *StrippedBasePtr =
5422 Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
5423
5424 // Avoid creating inttoptr of zero here: While LLVMs treatment of
5425 // inttoptr is generally conservative, this particular case is folded to
5426 // a null pointer, which will have incorrect provenance.
5427
5428 // gep (gep V, C), (sub 0, V) -> C
5429 // gep (gep V, C), (xor V, -1) -> C-1
5430 APInt Offset = IsNeg ? BasePtrOffset : BasePtrOffset - 1;
5431 if (PtrOp == StrippedBasePtr && !Offset.isZero()) {
5432 auto *CI = ConstantInt::get(GEPTy->getContext(), Offset);
5433 return ConstantExpr::getIntToPtr(CI, GEPTy);
5434 }
5435 }
5436 }
5437
5438 // Check to see if this is constant foldable.
5439 if (!isa<Constant>(Ptr) || !all_of(Indices, IsaPred<Constant>))
5440 return nullptr;
5441
5442 ArrayRef<Constant *> ConstIdxs =
5443 ArrayRef((Constant *const *)Indices.data(), Indices.size());
5444 auto *ConstGEP = ConstantExpr::getGetElementPtr(
5445 Q.DL, SrcTy, cast<Constant>(Ptr), ConstIdxs, NW);
5446 if (!ConstGEP)
5447 return ConstantFoldGetElementPtr(SrcTy, cast<Constant>(Ptr), std::nullopt,
5448 Indices);
5449
5450 return ConstantFoldConstant(ConstGEP, Q.DL);
5451}
5452
5454 GEPNoWrapFlags NW, const SimplifyQuery &Q) {
5455 return ::simplifyGEPInst(SrcTy, Ptr, Indices, NW, Q, RecursionLimit);
5456}
5457
5458/// Given operands for an InsertValueInst, see if we can fold the result.
5459/// If not, this returns null.
5461 ArrayRef<unsigned> Idxs,
5462 const SimplifyQuery &Q, unsigned) {
5463 if (Constant *CAgg = dyn_cast<Constant>(Agg))
5464 if (Constant *CVal = dyn_cast<Constant>(Val))
5465 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
5466
5467 // insertvalue x, poison, n -> x
5468 // insertvalue x, undef, n -> x if x cannot be poison
5469 if (isa<PoisonValue>(Val) ||
5470 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Agg)))
5471 return Agg;
5472
5473 // insertvalue x, (extractvalue y, n), n
5475 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
5476 EV->getIndices() == Idxs) {
5477 // insertvalue poison, (extractvalue y, n), n -> y
5478 // insertvalue undef, (extractvalue y, n), n -> y if y cannot be poison
5479 if (isa<PoisonValue>(Agg) ||
5480 (Q.isUndefValue(Agg) &&
5481 isGuaranteedNotToBePoison(EV->getAggregateOperand())))
5482 return EV->getAggregateOperand();
5483
5484 // insertvalue y, (extractvalue y, n), n -> y
5485 if (Agg == EV->getAggregateOperand())
5486 return Agg;
5487 }
5488
5489 return nullptr;
5490}
5491
5493 ArrayRef<unsigned> Idxs,
5494 const SimplifyQuery &Q) {
5495 return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
5496}
5497
5499 const SimplifyQuery &Q) {
5500 // Try to constant fold.
5501 auto *VecC = dyn_cast<Constant>(Vec);
5502 auto *ValC = dyn_cast<Constant>(Val);
5503 auto *IdxC = dyn_cast<Constant>(Idx);
5504 if (VecC && ValC && IdxC)
5505 return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
5506
5507 // For fixed-length vector, fold into poison if index is out of bounds.
5508 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
5509 if (isa<FixedVectorType>(Vec->getType()) &&
5510 CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
5511 return PoisonValue::get(Vec->getType());
5512 }
5513
5514 // If index is undef, it might be out of bounds (see above case)
5515 if (Q.isUndefValue(Idx))
5516 return PoisonValue::get(Vec->getType());
5517
5518 // If the scalar is poison, or it is undef and there is no risk of
5519 // propagating poison from the vector value, simplify to the vector value.
5520 if (isa<PoisonValue>(Val) ||
5521 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
5522 return Vec;
5523
5524 // Inserting the splatted value into a constant splat does nothing.
5525 if (VecC && ValC && VecC->getSplatValue() == ValC)
5526 return Vec;
5527
5528 // If we are extracting a value from a vector, then inserting it into the same
5529 // place, that's the input vector:
5530 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
5531 if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
5532 return Vec;
5533
5534 return nullptr;
5535}
5536
5537/// Given operands for an ExtractValueInst, see if we can fold the result.
5538/// If not, this returns null.
5540 const SimplifyQuery &, unsigned) {
5541 if (auto *CAgg = dyn_cast<Constant>(Agg))
5542 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
5543
5544 // extractvalue x, (insertvalue y, elt, n), n -> elt
5545 unsigned NumIdxs = Idxs.size();
5547 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
5548 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
5549 // Protect against insertvalue cycles in unreachable code.
5550 if (!VisitedSet.insert(IVI).second)
5551 break;
5552
5553 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
5554 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
5555 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
5556 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
5557 Idxs.slice(0, NumCommonIdxs)) {
5558 if (NumIdxs == NumInsertValueIdxs)
5559 return IVI->getInsertedValueOperand();
5560 break;
5561 }
5562 }
5563
5564 // Simplify umul_with_overflow where one operand is 1.
5565 Value *V;
5566 if (Idxs.size() == 1 &&
5567 (match(Agg,
5570 m_Value(V))))) {
5571 if (Idxs[0] == 0)
5572 return V;
5573 assert(Idxs[0] == 1 && "invalid index");
5574 return getFalse(CmpInst::makeCmpResultType(V->getType()));
5575 }
5576
5577 return nullptr;
5578}
5579
5581 const SimplifyQuery &Q) {
5582 return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
5583}
5584
5585/// Given operands for an ExtractElementInst, see if we can fold the result.
5586/// If not, this returns null.
5588 const SimplifyQuery &Q, unsigned) {
5589 auto *VecVTy = cast<VectorType>(Vec->getType());
5590 if (auto *CVec = dyn_cast<Constant>(Vec)) {
5591 if (auto *CIdx = dyn_cast<Constant>(Idx))
5592 return ConstantExpr::getExtractElement(CVec, CIdx);
5593
5594 if (Q.isUndefValue(Vec))
5595 return UndefValue::get(VecVTy->getElementType());
5596 }
5597
5598 // An undef extract index can be arbitrarily chosen to be an out-of-range
5599 // index value, which would result in the instruction being poison.
5600 if (Q.isUndefValue(Idx))
5601 return PoisonValue::get(VecVTy->getElementType());
5602
5603 // If extracting a specified index from the vector, see if we can recursively
5604 // find a previously computed scalar that was inserted into the vector.
5605 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
5606 // For fixed-length vector, fold into undef if index is out of bounds.
5607 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
5608 if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
5609 return PoisonValue::get(VecVTy->getElementType());
5610 // Handle case where an element is extracted from a splat.
5611 if (IdxC->getValue().ult(MinNumElts))
5612 if (auto *Splat = getSplatValue(Vec))
5613 return Splat;
5614 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
5615 return Elt;
5616 } else {
5617 // extractelt x, (insertelt y, elt, n), n -> elt
5618 // If the possibly-variable indices are trivially known to be equal
5619 // (because they are the same operand) then use the value that was
5620 // inserted directly.
5621 auto *IE = dyn_cast<InsertElementInst>(Vec);
5622 if (IE && IE->getOperand(2) == Idx)
5623 return IE->getOperand(1);
5624
5625 // The index is not relevant if our vector is a splat.
5626 if (Value *Splat = getSplatValue(Vec))
5627 return Splat;
5628 }
5629 return nullptr;
5630}
5631
5633 const SimplifyQuery &Q) {
5634 return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
5635}
5636
5637/// Return true if accessing the bit range of type Ty at Offset in a value of
5638/// type SrcTy is poison.
5639static bool isPoisonBitRange(Value *Offset, Type *Ty, Type *SrcTy,
5640 const SimplifyQuery &Q) {
5642 if (!C)
5643 return false;
5644
5645 // A poison offset makes the result poison. An undef offset can be chosen to
5646 // be out of range, which also makes the result poison.
5647 if (isa<PoisonValue>(C) || Q.isUndefValue(C))
5648 return true;
5649
5650 // Accessing bits past the end of the value is poison. This covers scalars and
5651 // fixed/scalable vectors with splat constants.
5652 uint64_t Off;
5653 if (match(C, m_ConstantInt(Off)) &&
5654 Off + Q.DL.getTypeSizeInBits(Ty->getScalarType()).getFixedValue() >
5655 Q.DL.getTypeSizeInBits(SrcTy->getScalarType()).getFixedValue())
5656 return true;
5657
5658 // Try harder for fixed-length vectors:
5659 // If every lane's offset is out of range or poison, the result is poison.
5661 for (unsigned I = 0,
5662 E = cast<FixedVectorType>(C->getType())->getNumElements();
5663 I != E; ++I)
5664 if (!isPoisonBitRange(C->getAggregateElement(I), Ty, SrcTy, Q))
5665 return false;
5666 return true;
5667 }
5668
5669 return false;
5670}
5671
5672/// Given operands for a BitInsertInst, see if we can fold the result.
5673/// If not, this returns null.
5675 const SimplifyQuery &Q, unsigned) {
5676 auto *CBase = dyn_cast<Constant>(Base);
5677 auto *CVal = dyn_cast<Constant>(Val);
5678 auto *COffset = dyn_cast<Constant>(Offset);
5679 if (CBase && CVal && COffset)
5680 if (Constant *C = ConstantFoldBitInsertOperands(CBase, CVal, COffset, Q.DL))
5681 return C;
5682
5683 // bitinsert x, y, poison/undef/out_of_range -> poison
5684 if (isPoisonBitRange(Offset, Val->getType(), Base->getType(), Q))
5685 return PoisonValue::get(Base->getType());
5686
5687 // bitinsert x, (bN y), n -> y, since any n != 0 is poison
5688 if (Val->getType() == Base->getType())
5689 return Val;
5690
5691 // bitinsert x, (bitextract ty, x, n), n -> x
5693 return Base;
5694
5695 return nullptr;
5696}
5697
5699 const SimplifyQuery &Q) {
5700 return ::simplifyBitInsertInst(Base, Val, Offset, Q, RecursionLimit);
5701}
5702
5703/// Given operands for a BitExtractInst, see if we can fold the result.
5704/// If not, this returns null.
5706 const SimplifyQuery &Q, unsigned) {
5707 auto *CSrc = dyn_cast<Constant>(Src);
5708 auto *COffset = dyn_cast<Constant>(Offset);
5709 if (CSrc && COffset)
5710 if (Constant *C = ConstantFoldBitExtractOperands(Ty, CSrc, COffset, Q.DL))
5711 return C;
5712
5713 // bitextract ty, x, poison/undef/out_of_range -> poison
5714 if (isPoisonBitRange(Offset, Ty, Src->getType(), Q))
5715 return PoisonValue::get(Ty);
5716
5717 // bitextract bN, (bN x), n -> x, since any n != 0 is poison
5718 if (Src->getType() == Ty)
5719 return Src;
5720
5721 // bitextract ty, (bitinsert x, (ty y), n), n -> y
5722 Value *Val;
5723 if (match(Src, m_BitInsert(m_Value(), m_Value(Val), m_Specific(Offset))) &&
5724 Val->getType() == Ty)
5725 return Val;
5726
5727 return nullptr;
5728}
5729
5731 const SimplifyQuery &Q) {
5732 return ::simplifyBitExtractInst(Ty, Src, Offset, Q, RecursionLimit);
5733}
5734
5735/// See if we can fold the given phi. If not, returns null.
5737 const SimplifyQuery &Q) {
5738 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
5739 // here, because the PHI we may succeed simplifying to was not
5740 // def-reachable from the original PHI!
5741
5742 // If all of the PHI's incoming values are the same then replace the PHI node
5743 // with the common value.
5744 Value *CommonValue = nullptr;
5745 bool HasPoisonInput = false;
5746 bool HasUndefInput = false;
5747 for (Value *Incoming : IncomingValues) {
5748 // If the incoming value is the phi node itself, it can safely be skipped.
5749 if (Incoming == PN)
5750 continue;
5751 if (isa<PoisonValue>(Incoming)) {
5752 HasPoisonInput = true;
5753 continue;
5754 }
5755 if (Q.isUndefValue(Incoming)) {
5756 // Remember that we saw an undef value, but otherwise ignore them.
5757 HasUndefInput = true;
5758 continue;
5759 }
5760 if (CommonValue && Incoming != CommonValue)
5761 return nullptr; // Not the same, bail out.
5762 CommonValue = Incoming;
5763 }
5764
5765 // If CommonValue is null then all of the incoming values were either undef,
5766 // poison or equal to the phi node itself.
5767 if (!CommonValue)
5768 return HasUndefInput ? UndefValue::get(PN->getType())
5769 : PoisonValue::get(PN->getType());
5770
5771 if (HasPoisonInput || HasUndefInput) {
5772 // If we have a PHI node like phi(X, undef, X), where X is defined by some
5773 // instruction, we cannot return X as the result of the PHI node unless it
5774 // dominates the PHI block.
5775 if (!valueDominatesPHI(CommonValue, PN, Q.DT))
5776 return nullptr;
5777
5778 // Make sure we do not replace an undef value with poison.
5779 if (HasUndefInput &&
5780 !isGuaranteedNotToBePoison(CommonValue, Q.AC, Q.CtxI, Q.DT))
5781 return nullptr;
5782 return CommonValue;
5783 }
5784
5785 return CommonValue;
5786}
5787
5788static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5789 const SimplifyQuery &Q, unsigned MaxRecurse) {
5790 if (auto *C = dyn_cast<Constant>(Op))
5791 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
5792
5793 if (auto *CI = dyn_cast<CastInst>(Op)) {
5794 auto *Src = CI->getOperand(0);
5795 Type *SrcTy = Src->getType();
5796 Type *MidTy = CI->getType();
5797 Type *DstTy = Ty;
5798 if (Src->getType() == Ty) {
5799 auto FirstOp = CI->getOpcode();
5800 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
5801 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
5802 &Q.DL) == Instruction::BitCast)
5803 return Src;
5804 }
5805 }
5806
5807 // bitcast x -> x
5808 if (CastOpc == Instruction::BitCast)
5809 if (Op->getType() == Ty)
5810 return Op;
5811
5812 // ptrtoaddr (ptradd (Ptr, X - ptrtoint/ptrtoaddr(Ptr))) -> X
5813 // This is also valid for ptrtoint, but only if the (now unused) ptrtoint
5814 // instruction is preserved for its provenance exposure side effect. As this
5815 // is currently not the case, only fold ptrtoaddr, which does not expose
5816 // provenance.
5817 Value *Ptr, *X;
5818 if (CastOpc == Instruction::PtrToAddr &&
5819 match(Op, m_PtrAdd(Q.DL, m_Value(Ptr),
5821 return X;
5822
5823 // Fold a value-preserving zext/sext of a trunc back to the original value.
5824 if (CastOpc == Instruction::ZExt || CastOpc == Instruction::SExt) {
5825 if (auto *Trunc = dyn_cast<TruncInst>(Op)) {
5826 Value *Src = Trunc->getOperand(0);
5827 bool NoWrap = CastOpc == Instruction::ZExt ? Trunc->hasNoUnsignedWrap()
5828 : Trunc->hasNoSignedWrap();
5829 if (Src->getType() == Ty && NoWrap)
5830 return Src;
5831 }
5832 }
5833
5834 return nullptr;
5835}
5836
5837Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5838 const SimplifyQuery &Q) {
5839 return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
5840}
5841
5842static Value *simplifyAddrSpaceCastInst(Value *Op, Type *Ty, bool IsNonNull,
5843 const SimplifyQuery &Q,
5844 unsigned MaxRecurse) {
5845 if (IsNonNull && isa<ConstantPointerNull>(Op) && Q.getFunction() &&
5847 Op->getType()->getPointerAddressSpace()))
5848 return PoisonValue::get(Ty);
5849
5850 return ::simplifyCastInst(Instruction::AddrSpaceCast, Op, Ty, Q, MaxRecurse);
5851}
5852
5854 const SimplifyQuery &Q) {
5855 return ::simplifyAddrSpaceCastInst(Op, Ty, IsNonNull, Q, RecursionLimit);
5856}
5857
5858/// For the given destination element of a shuffle, peek through shuffles to
5859/// match a root vector source operand that contains that element in the same
5860/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
5861static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
5862 int MaskVal, Value *RootVec,
5863 unsigned MaxRecurse) {
5864 if (!MaxRecurse--)
5865 return nullptr;
5866
5867 // Bail out if any mask value is undefined. That kind of shuffle may be
5868 // simplified further based on demanded bits or other folds.
5869 if (MaskVal == -1)
5870 return nullptr;
5871
5872 // The mask value chooses which source operand we need to look at next.
5873 int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
5874 int RootElt = MaskVal;
5875 Value *SourceOp = Op0;
5876 if (MaskVal >= InVecNumElts) {
5877 RootElt = MaskVal - InVecNumElts;
5878 SourceOp = Op1;
5879 }
5880
5881 // If the source operand is a shuffle itself, look through it to find the
5882 // matching root vector.
5883 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
5884 return foldIdentityShuffles(
5885 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
5886 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
5887 }
5888
5889 // The source operand is not a shuffle. Initialize the root vector value for
5890 // this shuffle if that has not been done yet.
5891 if (!RootVec)
5892 RootVec = SourceOp;
5893
5894 // Give up as soon as a source operand does not match the existing root value.
5895 if (RootVec != SourceOp)
5896 return nullptr;
5897
5898 // The element must be coming from the same lane in the source vector
5899 // (although it may have crossed lanes in intermediate shuffles).
5900 if (RootElt != DestElt)
5901 return nullptr;
5902
5903 return RootVec;
5904}
5905
5907 ArrayRef<int> Mask, Type *RetTy,
5908 const SimplifyQuery &Q,
5909 unsigned MaxRecurse) {
5910 if (all_of(Mask, equal_to(PoisonMaskElem)))
5911 return PoisonValue::get(RetTy);
5912
5913 auto *InVecTy = cast<VectorType>(Op0->getType());
5914 unsigned MaskNumElts = Mask.size();
5915 ElementCount InVecEltCount = InVecTy->getElementCount();
5916
5917 bool Scalable = InVecEltCount.isScalable();
5918
5919 SmallVector<int, 32> Indices;
5920 Indices.assign(Mask.begin(), Mask.end());
5921
5922 // Canonicalization: If mask does not select elements from an input vector,
5923 // replace that input vector with poison.
5924 if (!Scalable) {
5925 bool MaskSelects0 = false, MaskSelects1 = false;
5926 unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
5927 for (unsigned i = 0; i != MaskNumElts; ++i) {
5928 if (Indices[i] == -1)
5929 continue;
5930 if ((unsigned)Indices[i] < InVecNumElts)
5931 MaskSelects0 = true;
5932 else
5933 MaskSelects1 = true;
5934 }
5935 if (!MaskSelects0)
5936 Op0 = PoisonValue::get(InVecTy);
5937 if (!MaskSelects1)
5938 Op1 = PoisonValue::get(InVecTy);
5939 }
5940
5941 auto *Op0Const = dyn_cast<Constant>(Op0);
5942 auto *Op1Const = dyn_cast<Constant>(Op1);
5943
5944 // If all operands are constant, constant fold the shuffle. This
5945 // transformation depends on the value of the mask which is not known at
5946 // compile time for scalable vectors
5947 if (Op0Const && Op1Const)
5948 return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
5949
5950 // Canonicalization: if only one input vector is constant, it shall be the
5951 // second one. This transformation depends on the value of the mask which
5952 // is not known at compile time for scalable vectors
5953 if (!Scalable && Op0Const && !Op1Const) {
5954 std::swap(Op0, Op1);
5956 InVecEltCount.getKnownMinValue());
5957 }
5958
5959 // A splat of an inserted scalar constant becomes a vector constant:
5960 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
5961 // NOTE: We may have commuted above, so analyze the updated Indices, not the
5962 // original mask constant.
5963 // NOTE: This transformation depends on the value of the mask which is not
5964 // known at compile time for scalable vectors
5965 Constant *C;
5966 ConstantInt *IndexC;
5967 if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
5968 m_ConstantInt(IndexC)))) {
5969 // Match a splat shuffle mask of the insert index allowing undef elements.
5970 int InsertIndex = IndexC->getZExtValue();
5971 if (all_of(Indices, [InsertIndex](int MaskElt) {
5972 return MaskElt == InsertIndex || MaskElt == -1;
5973 })) {
5974 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
5975
5976 // Shuffle mask poisons become poison constant result elements.
5977 SmallVector<Constant *, 16> VecC(MaskNumElts, C);
5978 for (unsigned i = 0; i != MaskNumElts; ++i)
5979 if (Indices[i] == -1)
5980 VecC[i] = PoisonValue::get(C->getType());
5981 return ConstantVector::get(VecC);
5982 }
5983 }
5984
5985 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5986 // value type is same as the input vectors' type.
5987 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
5988 if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5989 all_equal(OpShuf->getShuffleMask()))
5990 return Op0;
5991
5992 // All remaining transformation depend on the value of the mask, which is
5993 // not known at compile time for scalable vectors.
5994 if (Scalable)
5995 return nullptr;
5996
5997 // Don't fold a shuffle with undef mask elements. This may get folded in a
5998 // better way using demanded bits or other analysis.
5999 // TODO: Should we allow this?
6000 if (is_contained(Indices, -1))
6001 return nullptr;
6002
6003 // Check if every element of this shuffle can be mapped back to the
6004 // corresponding element of a single root vector. If so, we don't need this
6005 // shuffle. This handles simple identity shuffles as well as chains of
6006 // shuffles that may widen/narrow and/or move elements across lanes and back.
6007 Value *RootVec = nullptr;
6008 for (unsigned i = 0; i != MaskNumElts; ++i) {
6009 // Note that recursion is limited for each vector element, so if any element
6010 // exceeds the limit, this will fail to simplify.
6011 RootVec =
6012 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
6013
6014 // We can't replace a widening/narrowing shuffle with one of its operands.
6015 if (!RootVec || RootVec->getType() != RetTy)
6016 return nullptr;
6017 }
6018 return RootVec;
6019}
6020
6021/// Given operands for a ShuffleVectorInst, fold the result or return null.
6023 ArrayRef<int> Mask, Type *RetTy,
6024 const SimplifyQuery &Q) {
6025 return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
6026}
6027
6029 const SimplifyQuery &Q) {
6030 if (auto *C = dyn_cast<Constant>(Op))
6031 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
6032 return nullptr;
6033}
6034
6035/// Given the operand for an FNeg, see if we can fold the result. If not, this
6036/// returns null.
6038 const SimplifyQuery &Q, unsigned MaxRecurse) {
6039 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
6040 return C;
6041
6042 Value *X;
6043 // fneg (fneg X) ==> X
6044 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
6046 return X;
6047
6048 return nullptr;
6049}
6050
6052 const SimplifyQuery &Q) {
6053 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
6054}
6055
6056/// Try to propagate existing NaN values when possible. If not, replace the
6057/// constant or elements in the constant with a canonical NaN.
6059 Type *Ty = In->getType();
6060 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
6061 unsigned NumElts = VecTy->getNumElements();
6062 SmallVector<Constant *, 32> NewC(NumElts);
6063 for (unsigned i = 0; i != NumElts; ++i) {
6064 Constant *EltC = In->getAggregateElement(i);
6065 // Poison elements propagate. NaN propagates except signaling is quieted.
6066 // Replace unknown or undef elements with canonical NaN.
6067 if (EltC && isa<PoisonValue>(EltC))
6068 NewC[i] = EltC;
6069 else if (EltC && EltC->isNaN())
6070 NewC[i] = ConstantFP::get(
6071 EltC->getType(), cast<ConstantFP>(EltC)->getValue().makeQuiet());
6072 else
6073 NewC[i] = ConstantFP::getNaN(VecTy->getElementType());
6074 }
6075 return ConstantVector::get(NewC);
6076 }
6077
6078 // If it is not a fixed vector, but not a simple NaN either, return a
6079 // canonical NaN.
6080 if (!In->isNaN())
6081 return ConstantFP::getNaN(Ty);
6082
6083 // If we known this is a NaN, and it's scalable vector, we must have a splat
6084 // on our hands. Grab that before splatting a QNaN constant.
6085 if (isa<ScalableVectorType>(Ty)) {
6086 auto *Splat = In->getSplatValue();
6087 assert(Splat && Splat->isNaN() &&
6088 "Found a scalable-vector NaN but not a splat");
6089 In = Splat;
6090 }
6091
6092 // Propagate an existing QNaN constant. If it is an SNaN, make it quiet, but
6093 // preserve the sign/payload.
6094 return ConstantFP::get(Ty, cast<ConstantFP>(In)->getValue().makeQuiet());
6095}
6096
6097/// Perform folds that are common to any floating-point operation. This implies
6098/// transforms based on poison/undef/NaN because the operation itself makes no
6099/// difference to the result.
6101 const SimplifyQuery &Q,
6102 fp::ExceptionBehavior ExBehavior,
6103 RoundingMode Rounding) {
6104 // Poison is independent of anything else. It always propagates from an
6105 // operand to a math result.
6107 return PoisonValue::get(Ops[0]->getType());
6108
6109 for (Value *V : Ops) {
6110 bool IsNan = match(V, m_NaN());
6111 bool IsInf = match(V, m_Inf());
6112 bool IsUndef = Q.isUndefValue(V);
6113
6114 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
6115 // (an undef operand can be chosen to be Nan/Inf), then the result of
6116 // this operation is poison.
6117 if (FMF.noNaNs() && (IsNan || IsUndef))
6118 return PoisonValue::get(V->getType());
6119 if (FMF.noInfs() && (IsInf || IsUndef))
6120 return PoisonValue::get(V->getType());
6121
6122 if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
6123 // Undef does not propagate because undef means that all bits can take on
6124 // any value. If this is undef * NaN for example, then the result values
6125 // (at least the exponent bits) are limited. Assume the undef is a
6126 // canonical NaN and propagate that.
6127 if (IsUndef)
6128 return ConstantFP::getNaN(V->getType());
6129 if (IsNan)
6130 return propagateNaN(cast<Constant>(V));
6131 } else if (ExBehavior != fp::ebStrict) {
6132 if (IsNan)
6133 return propagateNaN(cast<Constant>(V));
6134 }
6135 }
6136 return nullptr;
6137}
6138
6139/// Given operands for an FAdd, see if we can fold the result. If not, this
6140/// returns null.
6141static Value *
6143 const SimplifyQuery &Q, unsigned MaxRecurse,
6146 if (isDefaultFPEnvironment(ExBehavior, Rounding))
6147 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
6148 return C;
6149
6150 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6151 return C;
6152
6153 // fadd X, -0 ==> X
6154 // With strict/constrained FP, we have these possible edge cases that do
6155 // not simplify to Op0:
6156 // fadd SNaN, -0.0 --> QNaN
6157 // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
6158 if (canIgnoreSNaN(ExBehavior, FMF) &&
6160 FMF.noSignedZeros()))
6161 if (match(Op1, m_NegZeroFP()))
6162 return Op0;
6163
6164 // fadd X, 0 ==> X, when we know X is not -0
6165 if (canIgnoreSNaN(ExBehavior, FMF))
6166 if (match(Op1, m_PosZeroFP()) &&
6167 (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, Q)))
6168 return Op0;
6169
6170 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
6171 return nullptr;
6172
6173 if (FMF.noNaNs()) {
6174 // With nnan: X + {+/-}Inf --> {+/-}Inf
6175 if (match(Op1, m_Inf()))
6176 return Op1;
6177
6178 // With nnan: -X + X --> 0.0 (and commuted variant)
6179 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
6180 // Negative zeros are allowed because we always end up with positive zero:
6181 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
6182 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
6183 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
6184 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
6185 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
6186 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
6187 return ConstantFP::getZero(Op0->getType());
6188
6189 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
6190 if (match(Op0, m_FNegOrFSubNegZero(m_Specific(Op1))) ||
6192 return ConstantFP::getZero(Op0->getType());
6193 }
6194
6195 // (X - Y) + Y --> X
6196 // Y + (X - Y) --> X
6197 Value *X;
6198 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
6199 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
6200 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
6201 return X;
6202
6203 return nullptr;
6204}
6205
6206/// Given operands for an FSub, see if we can fold the result. If not, this
6207/// returns null.
6208static Value *
6210 const SimplifyQuery &Q, unsigned MaxRecurse,
6213 if (isDefaultFPEnvironment(ExBehavior, Rounding))
6214 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
6215 return C;
6216
6217 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6218 return C;
6219
6220 // fsub X, +0 ==> X
6221 if (canIgnoreSNaN(ExBehavior, FMF) &&
6223 FMF.noSignedZeros()))
6224 if (match(Op1, m_PosZeroFP()))
6225 return Op0;
6226
6227 // fsub X, -0 ==> X, when we know X is not -0
6228 if (canIgnoreSNaN(ExBehavior, FMF))
6229 if (match(Op1, m_NegZeroFP()) &&
6230 (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, Q)))
6231 return Op0;
6232
6233 // fsub -0.0, (fsub -0.0, X) ==> X
6234 // fsub -0.0, (fneg X) ==> X
6235 // With strict/constrained FP, round toward negative (or dynamic rounding,
6236 // which may select it) can change the sign of a zero result. Preserve the
6237 // operation unless signed zeros are ignored with the nsz flag.
6238 Value *X;
6239 if (canIgnoreSNaN(ExBehavior, FMF) &&
6241 FMF.noSignedZeros()))
6242 if (match(Op0, m_NegZeroFP()) &&
6244 return X;
6245
6246 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
6247 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
6248 if (canIgnoreSNaN(ExBehavior, FMF))
6249 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
6250 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
6251 match(Op1, m_FNeg(m_Value(X)))))
6252 return X;
6253
6254 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
6255 return nullptr;
6256
6257 if (FMF.noNaNs()) {
6258 // fsub nnan x, x ==> 0.0
6259 if (Op0 == Op1)
6260 return Constant::getNullValue(Op0->getType());
6261
6262 // With nnan: {+/-}Inf - X --> {+/-}Inf
6263 if (match(Op0, m_Inf()))
6264 return Op0;
6265
6266 // With nnan: X - {+/-}Inf --> {-/+}Inf
6267 if (match(Op1, m_Inf()))
6268 return foldConstant(Instruction::FNeg, Op1, Q);
6269 }
6270
6271 // Y - (Y - X) --> X
6272 // (X + Y) - Y --> X
6273 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
6274 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
6275 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
6276 return X;
6277
6278 return nullptr;
6279}
6280
6282 const SimplifyQuery &Q, unsigned MaxRecurse,
6283 fp::ExceptionBehavior ExBehavior,
6284 RoundingMode Rounding) {
6285 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6286 return C;
6287
6288 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
6289 return nullptr;
6290
6291 // Canonicalize special constants as operand 1.
6292 if (match(Op0, m_FPOne()) || match(Op0, m_AnyZeroFP()))
6293 std::swap(Op0, Op1);
6294
6295 // X * 1.0 --> X
6296 if (match(Op1, m_FPOne()))
6297 return Op0;
6298
6299 if (match(Op1, m_AnyZeroFP())) {
6300 // X * 0.0 --> 0.0 (with nnan and nsz)
6301 if (FMF.noNaNs() && FMF.noSignedZeros())
6302 return ConstantFP::getZero(Op0->getType());
6303
6305 if (Known.isKnownNever(fcInf | fcNan)) {
6306 // if nsz is set, return 0.0
6307 if (FMF.noSignedZeros())
6308 return ConstantFP::getZero(Op0->getType());
6309 // +normal number * (-)0.0 --> (-)0.0
6310 if (Known.getSignBit() == false)
6311 return Op1;
6312 // -normal number * (-)0.0 --> -(-)0.0
6313 if (Known.getSignBit() == true)
6314 return foldConstant(Instruction::FNeg, Op1, Q);
6315 }
6316 }
6317
6318 // sqrt(X) * sqrt(X) --> X, if we can:
6319 // 1. Remove the intermediate rounding (reassociate).
6320 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
6321 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
6322 Value *X;
6323 if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
6324 FMF.noNaNs() && FMF.noSignedZeros())
6325 return X;
6326
6327 return nullptr;
6328}
6329
6330/// Given the operands for an FMul, see if we can fold the result
6331static Value *
6333 const SimplifyQuery &Q, unsigned MaxRecurse,
6336 if (isDefaultFPEnvironment(ExBehavior, Rounding))
6337 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
6338 return C;
6339
6340 // Now apply simplifications that do not require rounding.
6341 return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
6342}
6343
6345 const SimplifyQuery &Q,
6346 fp::ExceptionBehavior ExBehavior,
6347 RoundingMode Rounding) {
6348 return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6349 Rounding);
6350}
6351
6353 const SimplifyQuery &Q,
6354 fp::ExceptionBehavior ExBehavior,
6355 RoundingMode Rounding) {
6356 return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6357 Rounding);
6358}
6359
6361 const SimplifyQuery &Q,
6362 fp::ExceptionBehavior ExBehavior,
6363 RoundingMode Rounding) {
6364 return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6365 Rounding);
6366}
6367
6369 const SimplifyQuery &Q,
6370 fp::ExceptionBehavior ExBehavior,
6371 RoundingMode Rounding) {
6372 return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6373 Rounding);
6374}
6375
6376static Value *
6378 const SimplifyQuery &Q, unsigned,
6381 if (isDefaultFPEnvironment(ExBehavior, Rounding))
6382 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
6383 return C;
6384
6385 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6386 return C;
6387
6388 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
6389 return nullptr;
6390
6391 // X / 1.0 -> X
6392 if (match(Op1, m_FPOne()))
6393 return Op0;
6394
6395 // 0 / X -> 0
6396 // Requires that NaNs are off (X could be zero) and signed zeroes are
6397 // ignored (X could be positive or negative, so the output sign is unknown).
6398 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
6399 return ConstantFP::getZero(Op0->getType());
6400
6401 if (FMF.noNaNs()) {
6402 // X / X -> 1.0 is legal when NaNs are ignored.
6403 // We can ignore infinities because INF/INF is NaN.
6404 if (Op0 == Op1)
6405 return ConstantFP::get(Op0->getType(), 1.0);
6406
6407 // (X * Y) / Y --> X if we can reassociate to the above form.
6408 Value *X;
6409 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
6410 return X;
6411
6412 // -X / X -> -1.0 and
6413 // X / -X -> -1.0 are legal when NaNs are ignored.
6414 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored, so
6415 // -X can be fneg X or fsub +-0.0, X.
6416 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
6417 match(Op1, m_FNegNSZ(m_Specific(Op0))) ||
6418 match(Op0, m_FNeg(m_Specific(Op1))) ||
6419 match(Op1, m_FNeg(m_Specific(Op0))))
6420 return ConstantFP::get(Op0->getType(), -1.0);
6421
6422 // nnan ninf X / [-]0.0 -> poison
6423 if (FMF.noInfs() && match(Op1, m_AnyZeroFP()))
6424 return PoisonValue::get(Op1->getType());
6425 }
6426
6427 return nullptr;
6428}
6429
6431 const SimplifyQuery &Q,
6432 fp::ExceptionBehavior ExBehavior,
6433 RoundingMode Rounding) {
6434 return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6435 Rounding);
6436}
6437
6438static Value *
6440 const SimplifyQuery &Q, unsigned,
6443 if (isDefaultFPEnvironment(ExBehavior, Rounding))
6444 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
6445 return C;
6446
6447 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6448 return C;
6449
6450 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
6451 return nullptr;
6452
6453 // Unlike fdiv, the result of frem always matches the sign of the dividend.
6454 // The constant match may include undef elements in a vector, so return a full
6455 // zero constant as the result.
6456 if (FMF.noNaNs()) {
6457 // +0 % X -> 0
6458 if (match(Op0, m_PosZeroFP()))
6459 return ConstantFP::getZero(Op0->getType());
6460 // -0 % X -> -0
6461 if (match(Op0, m_NegZeroFP()))
6462 return ConstantFP::getNegativeZero(Op0->getType());
6463 }
6464
6465 return nullptr;
6466}
6467
6469 const SimplifyQuery &Q,
6470 fp::ExceptionBehavior ExBehavior,
6471 RoundingMode Rounding) {
6472 return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6473 Rounding);
6474}
6475
6476//=== Helper functions for higher up the class hierarchy.
6477
6478/// Given the operand for a UnaryOperator, see if we can fold the result.
6479/// If not, this returns null.
6480static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
6481 unsigned MaxRecurse) {
6482 switch (Opcode) {
6483 case Instruction::FNeg:
6484 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
6485 default:
6486 llvm_unreachable("Unexpected opcode");
6487 }
6488}
6489
6490/// Given the operand for a UnaryOperator, see if we can fold the result.
6491/// If not, this returns null.
6492/// Try to use FastMathFlags when folding the result.
6493static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
6494 const FastMathFlags &FMF, const SimplifyQuery &Q,
6495 unsigned MaxRecurse) {
6496 switch (Opcode) {
6497 case Instruction::FNeg:
6498 return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
6499 default:
6500 return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
6501 }
6502}
6503
6504Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
6505 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
6506}
6507
6509 const SimplifyQuery &Q) {
6510 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
6511}
6512
6513/// Given operands for a BinaryOperator, see if we can fold the result.
6514/// If not, this returns null.
6515static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6516 const SimplifyQuery &Q, unsigned MaxRecurse) {
6517 switch (Opcode) {
6518 case Instruction::Add:
6519 return simplifyAddInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6520 MaxRecurse);
6521 case Instruction::Sub:
6522 return simplifySubInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6523 MaxRecurse);
6524 case Instruction::Mul:
6525 return simplifyMulInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6526 MaxRecurse);
6527 case Instruction::SDiv:
6528 return simplifySDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6529 case Instruction::UDiv:
6530 return simplifyUDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6531 case Instruction::SRem:
6532 return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
6533 case Instruction::URem:
6534 return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
6535 case Instruction::Shl:
6536 return simplifyShlInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6537 MaxRecurse);
6538 case Instruction::LShr:
6539 return simplifyLShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6540 case Instruction::AShr:
6541 return simplifyAShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
6542 case Instruction::And:
6543 return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
6544 case Instruction::Or:
6545 return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
6546 case Instruction::Xor:
6547 return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
6548 case Instruction::FAdd:
6549 return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6550 case Instruction::FSub:
6551 return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6552 case Instruction::FMul:
6553 return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6554 case Instruction::FDiv:
6555 return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6556 case Instruction::FRem:
6557 return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6558 default:
6559 llvm_unreachable("Unexpected opcode");
6560 }
6561}
6562
6563/// Given operands for a BinaryOperator, see if we can fold the result.
6564/// If not, this returns null.
6565/// Try to use FastMathFlags when folding the result.
6566static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6567 const FastMathFlags &FMF, const SimplifyQuery &Q,
6568 unsigned MaxRecurse) {
6569 switch (Opcode) {
6570 case Instruction::FAdd:
6571 return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
6572 case Instruction::FSub:
6573 return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
6574 case Instruction::FMul:
6575 return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
6576 case Instruction::FDiv:
6577 return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
6578 case Instruction::FRem:
6579 return simplifyFRemInst(LHS, RHS, FMF, Q, MaxRecurse);
6580 default:
6581 return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
6582 }
6583}
6584
6585Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6586 const SimplifyQuery &Q) {
6587 return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
6588}
6589
6590Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6591 FastMathFlags FMF, const SimplifyQuery &Q) {
6592 return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
6593}
6594
6595/// Given operands for a CmpInst, see if we can fold the result.
6597 const SimplifyQuery &Q, unsigned MaxRecurse) {
6599 return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
6600 return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6601}
6602
6604 const SimplifyQuery &Q) {
6605 return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
6606}
6607
6609 switch (ID) {
6610 default:
6611 return false;
6612
6613 // Unary idempotent: f(f(x)) = f(x)
6614 case Intrinsic::fabs:
6615 case Intrinsic::floor:
6616 case Intrinsic::ceil:
6617 case Intrinsic::trunc:
6618 case Intrinsic::rint:
6619 case Intrinsic::nearbyint:
6620 case Intrinsic::round:
6621 case Intrinsic::roundeven:
6622 case Intrinsic::canonicalize:
6623 case Intrinsic::arithmetic_fence:
6624 return true;
6625 }
6626}
6627
6628/// Return true if the intrinsic rounds a floating-point value to an integral
6629/// floating-point value (not an integer type).
6631 switch (ID) {
6632 default:
6633 return false;
6634
6635 case Intrinsic::floor:
6636 case Intrinsic::ceil:
6637 case Intrinsic::trunc:
6638 case Intrinsic::rint:
6639 case Intrinsic::nearbyint:
6640 case Intrinsic::round:
6641 case Intrinsic::roundeven:
6642 return true;
6643 }
6644}
6645
6647 const DataLayout &DL) {
6648 GlobalValue *PtrSym;
6649 APInt PtrOffset;
6650 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
6651 return nullptr;
6652
6653 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
6654
6655 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
6656 if (!OffsetConstInt || OffsetConstInt->getBitWidth() > 64)
6657 return nullptr;
6658
6659 APInt OffsetInt = OffsetConstInt->getValue().sextOrTrunc(
6660 DL.getIndexTypeSizeInBits(Ptr->getType()));
6661 if (OffsetInt.srem(4) != 0)
6662 return nullptr;
6663
6664 Constant *Loaded =
6665 ConstantFoldLoadFromConstPtr(Ptr, Int32Ty, std::move(OffsetInt), DL);
6666 if (!Loaded)
6667 return nullptr;
6668
6669 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
6670 if (!LoadedCE)
6671 return nullptr;
6672
6673 if (LoadedCE->getOpcode() == Instruction::Trunc) {
6674 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6675 if (!LoadedCE)
6676 return nullptr;
6677 }
6678
6679 if (LoadedCE->getOpcode() != Instruction::Sub)
6680 return nullptr;
6681
6682 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6683 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
6684 return nullptr;
6685 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
6686
6687 Constant *LoadedRHS = LoadedCE->getOperand(1);
6688 GlobalValue *LoadedRHSSym;
6689 APInt LoadedRHSOffset;
6690 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
6691 DL) ||
6692 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
6693 return nullptr;
6694
6695 return LoadedLHSPtr;
6696}
6697
6698// TODO: Need to pass in FastMathFlags
6699static Value *simplifyLdexp(Value *Op0, Value *Op1, const SimplifyQuery &Q,
6700 bool IsStrict) {
6701 // ldexp(undef, x) -> nan
6702 if (Q.isUndefValue(Op0))
6703 return ConstantFP::getNaN(Op0->getType());
6704
6705 if (!IsStrict) {
6706 // TODO: Could insert a canonicalize for strict
6707
6708 // ldexp(x, undef) -> x
6709 if (Q.isUndefValue(Op1))
6710 return Op0;
6711 }
6712
6713 const APFloat *C = nullptr;
6715
6716 // These cases should be safe, even with strictfp.
6717 // ldexp(0.0, x) -> 0.0
6718 // ldexp(-0.0, x) -> -0.0
6719 // ldexp(inf, x) -> inf
6720 // ldexp(-inf, x) -> -inf
6721 if (C && (C->isZero() || C->isInfinity()))
6722 return Op0;
6723
6724 // These are canonicalization dropping, could do it if we knew how we could
6725 // ignore denormal flushes and target handling of nan payload bits.
6726 if (IsStrict)
6727 return nullptr;
6728
6729 // TODO: Could quiet this with strictfp if the exception mode isn't strict.
6730 if (C && C->isNaN())
6731 return ConstantFP::get(Op0->getType(), C->makeQuiet());
6732
6733 // ldexp(x, 0) -> x
6734
6735 // TODO: Could fold this if we know the exception mode isn't
6736 // strict, we know the denormal mode and other target modes.
6737 if (match(Op1, PatternMatch::m_ZeroInt()))
6738 return Op0;
6739
6740 return nullptr;
6741}
6742
6744 FastMathFlags FMF,
6745 const SimplifyQuery &Q) {
6746 // Idempotent functions return the same result when called repeatedly.
6747 if (isIdempotent(IID))
6748 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
6749 if (II->getIntrinsicID() == IID)
6750 return II;
6751
6752 if (removesFPFraction(IID)) {
6753 // Converting from int or calling a rounding function always results in a
6754 // finite integral number or infinity. For those inputs, rounding functions
6755 // always return the same value, so the (2nd) rounding is eliminated. Ex:
6756 // floor (sitofp x) -> sitofp x
6757 // round (ceil x) -> ceil x
6758 auto *II = dyn_cast<IntrinsicInst>(Op0);
6759 if ((II && removesFPFraction(II->getIntrinsicID())) ||
6760 match(Op0, m_IToFP(m_Value())))
6761 return Op0;
6762 }
6763
6764 Value *X;
6765 switch (IID) {
6766 case Intrinsic::fabs: {
6767 KnownFPClass KnownClass = computeKnownFPClass(Op0, fcAllFlags, Q);
6768 if (KnownClass.getSignBit() == false)
6769 return Op0;
6770
6771 if (KnownClass.cannotBeOrderedLessThanZero() &&
6772 KnownClass.isKnownNeverNaN() && FMF.noSignedZeros())
6773 return Op0;
6774
6775 break;
6776 }
6777 case Intrinsic::bswap:
6778 // bswap(bswap(x)) -> x
6779 if (match(Op0, m_BSwap(m_Value(X))))
6780 return X;
6781 break;
6782 case Intrinsic::bitreverse:
6783 // bitreverse(bitreverse(x)) -> x
6784 if (match(Op0, m_BitReverse(m_Value(X))))
6785 return X;
6786 break;
6787 case Intrinsic::ctpop: {
6788 // ctpop(X) -> 1 iff X is non-zero power of 2.
6789 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero=*/false, Q))
6790 return ConstantInt::get(Op0->getType(), 1);
6791 // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
6792 // ctpop(and X, 1) --> and X, 1
6793 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6795 Q))
6796 return Op0;
6797 break;
6798 }
6799 case Intrinsic::exp:
6800 // exp(log(x)) -> x
6801 if (FMF.allowReassoc() &&
6803 return X;
6804 break;
6805 case Intrinsic::exp2:
6806 // exp2(log2(x)) -> x
6807 if (FMF.allowReassoc() &&
6809 return X;
6810 break;
6811 case Intrinsic::exp10:
6812 // exp10(log10(x)) -> x
6813 if (FMF.allowReassoc() &&
6815 return X;
6816 break;
6817 case Intrinsic::log:
6818 // log(exp(x)) -> x
6819 if (FMF.allowReassoc() &&
6821 return X;
6822 break;
6823 case Intrinsic::log2:
6824 // log2(exp2(x)) -> x
6825 if (FMF.allowReassoc() &&
6827 match(Op0,
6829 return X;
6830 break;
6831 case Intrinsic::log10:
6832 // log10(pow(10.0, x)) -> x
6833 // log10(exp10(x)) -> x
6834 if (FMF.allowReassoc() &&
6836 match(Op0,
6838 return X;
6839 break;
6840 case Intrinsic::vector_reverse:
6841 // vector.reverse(vector.reverse(x)) -> x
6842 if (match(Op0, m_VecReverse(m_Value(X))))
6843 return X;
6844 // vector.reverse(splat(X)) -> splat(X)
6845 if (isSplatValue(Op0))
6846 return Op0;
6847 break;
6848 case Intrinsic::structured_gep:
6849 return Op0;
6850 default:
6851 break;
6852 }
6853
6854 return nullptr;
6855}
6856
6857/// Given a min/max intrinsic, see if it can be removed based on having an
6858/// operand that is another min/max intrinsic with shared operand(s). The caller
6859/// is expected to swap the operand arguments to handle commutation.
6861 Value *X, *Y;
6862 if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
6863 return nullptr;
6864
6865 auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
6866 if (!MM0)
6867 return nullptr;
6868 Intrinsic::ID IID0 = MM0->getIntrinsicID();
6869
6870 if (Op1 == X || Op1 == Y ||
6872 // max (max X, Y), X --> max X, Y
6873 if (IID0 == IID)
6874 return MM0;
6875 // max (min X, Y), X --> X
6876 if (IID0 == getInverseMinMaxIntrinsic(IID))
6877 return Op1;
6878 }
6879 return nullptr;
6880}
6881
6882/// Given a min/max intrinsic, see if it can be removed based on having an
6883/// operand that is another min/max intrinsic with shared operand(s). The caller
6884/// is expected to swap the operand arguments to handle commutation.
6886 Value *Op1, unsigned MaxRecurse) {
6887 auto IsMinimumMaximumIntrinsic = [](Intrinsic::ID ID) {
6888 switch (ID) {
6889 case Intrinsic::maxnum:
6890 case Intrinsic::minnum:
6891 case Intrinsic::maximum:
6892 case Intrinsic::minimum:
6893 case Intrinsic::maximumnum:
6894 case Intrinsic::minimumnum:
6895 return true;
6896 default:
6897 return false;
6898 }
6899 };
6900
6901 assert(IsMinimumMaximumIntrinsic(IID) && "Unsupported intrinsic");
6902
6903 auto *M0 = dyn_cast<IntrinsicInst>(Op0);
6904 // If Op0 is not the same intrinsic as IID, do not process.
6905 // This is a difference with integer min/max handling. We do not process the
6906 // case like max(min(X,Y),min(X,Y)) => min(X,Y). But it can be handled by GVN.
6907 if (!M0 || M0->getIntrinsicID() != IID)
6908 return nullptr;
6909 Value *X0 = M0->getOperand(0);
6910 Value *Y0 = M0->getOperand(1);
6911 // Simple case, m(m(X,Y), X) => m(X, Y)
6912 // m(m(X,Y), Y) => m(X, Y)
6913 // For minimum/maximum, X is NaN => m(NaN, Y) == NaN and m(NaN, NaN) == NaN.
6914 // For minimum/maximum, Y is NaN => m(X, NaN) == NaN and m(NaN, NaN) == NaN.
6915 // For minnum/maxnum, X is NaN => m(NaN, Y) == Y and m(Y, Y) == Y.
6916 // For minnum/maxnum, Y is NaN => m(X, NaN) == X and m(X, NaN) == X.
6917 if (X0 == Op1 || Y0 == Op1)
6918 return M0;
6919
6920 // m(m(X, Y), Z) --> m(X, Y) if m(X, Z) == X or m(Y, Z) == Y.
6921 if (MaxRecurse--) {
6922 if (foldMinimumMaximumSharedOp(IID, X0, Op1, MaxRecurse) == X0 ||
6923 foldMinimumMaximumSharedOp(IID, Y0, Op1, MaxRecurse) == Y0)
6924 return M0;
6925 }
6926
6927 auto *M1 = dyn_cast<IntrinsicInst>(Op1);
6928 if (!M1 || !IsMinimumMaximumIntrinsic(M1->getIntrinsicID()))
6929 return nullptr;
6930 Value *X1 = M1->getOperand(0);
6931 Value *Y1 = M1->getOperand(1);
6932 Intrinsic::ID IID1 = M1->getIntrinsicID();
6933 // we have a case m(m(X,Y),m'(X,Y)) taking into account m' is commutative.
6934 // if m' is m or inversion of m => m(m(X,Y),m'(X,Y)) == m(X,Y).
6935 // For minimum/maximum, X is NaN => m(NaN,Y) == m'(NaN, Y) == NaN.
6936 // For minimum/maximum, Y is NaN => m(X,NaN) == m'(X, NaN) == NaN.
6937 // For minnum/maxnum, X is NaN => m(NaN,Y) == m'(NaN, Y) == Y.
6938 // For minnum/maxnum, Y is NaN => m(X,NaN) == m'(X, NaN) == X.
6939 if ((X0 == X1 && Y0 == Y1) || (X0 == Y1 && Y0 == X1))
6940 if (IID1 == IID || getInverseMinMaxIntrinsic(IID1) == IID)
6941 return M0;
6942
6943 return nullptr;
6944}
6945
6950 // For undef/poison, we can choose to either propgate undef/poison or
6951 // use the LHS value depending on what will allow more optimization.
6953};
6954// Get the optimized value for a min/max instruction with a single constant
6955// input (either undef or scalar constantFP). The result may indicate to
6956// use the non-const LHS value, use a new constant value instead (with NaNs
6957// quieted), or to choose either option in the case of undef/poison.
6959 const Intrinsic::ID IID,
6960 FastMathFlags FMF,
6961 Constant **OutNewConstVal) {
6962 assert(OutNewConstVal != nullptr);
6963
6964 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
6965 bool PropagateSNaN = IID == Intrinsic::minnum || IID == Intrinsic::maxnum;
6966 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum ||
6967 IID == Intrinsic::minimumnum;
6968
6969 // min/max(x, poison) -> either x or poison
6970 if (isa<UndefValue>(RHSConst)) {
6971 *OutNewConstVal = const_cast<Constant *>(RHSConst);
6973 }
6974
6975 const ConstantFP *CFP = dyn_cast<ConstantFP>(RHSConst);
6976 if (!CFP)
6978 APFloat CAPF = CFP->getValueAPF();
6979
6980 // minnum(x, qnan) -> x
6981 // maxnum(x, qnan) -> x
6982 // minnum(x, snan) -> qnan
6983 // maxnum(x, snan) -> qnan
6984 // minimum(X, nan) -> qnan
6985 // maximum(X, nan) -> qnan
6986 // minimumnum(X, nan) -> x
6987 // maximumnum(X, nan) -> x
6988 if (CAPF.isNaN()) {
6989 if (PropagateNaN || (PropagateSNaN && CAPF.isSignaling())) {
6990 *OutNewConstVal = ConstantFP::get(CFP->getType(), CAPF.makeQuiet());
6992 }
6994 }
6995
6996 if (CAPF.isInfinity() || (FMF.noInfs() && CAPF.isLargest())) {
6997 // minnum(X, -inf) -> -inf (ignoring sNaN -> qNaN propagation)
6998 // maxnum(X, +inf) -> +inf (ignoring sNaN -> qNaN propagation)
6999 // minimum(X, -inf) -> -inf if nnan
7000 // maximum(X, +inf) -> +inf if nnan
7001 // minimumnum(X, -inf) -> -inf
7002 // maximumnum(X, +inf) -> +inf
7003 if (CAPF.isNegative() == IsMin && (!PropagateNaN || FMF.noNaNs())) {
7004 *OutNewConstVal = const_cast<Constant *>(RHSConst);
7006 }
7007
7008 // minnum(X, +inf) -> X if nnan
7009 // maxnum(X, -inf) -> X if nnan
7010 // minimum(X, +inf) -> X (ignoring quieting of sNaNs)
7011 // maximum(X, -inf) -> X (ignoring quieting of sNaNs)
7012 // minimumnum(X, +inf) -> X if nnan
7013 // maximumnum(X, -inf) -> X if nnan
7014 if (CAPF.isNegative() != IsMin && (PropagateNaN || FMF.noNaNs()))
7016 }
7018}
7019
7021 Value *Op0, Value *Op1) {
7024 unsigned Width = ReturnType->getPrimitiveSizeInBits();
7025
7026 // All false predicate or reduction of neutral values ==> neutral result.
7027 switch (IID) {
7028 case Intrinsic::aarch64_sve_eorv:
7029 case Intrinsic::aarch64_sve_orv:
7030 case Intrinsic::aarch64_sve_saddv:
7031 case Intrinsic::aarch64_sve_uaddv:
7032 case Intrinsic::aarch64_sve_umaxv:
7033 if ((C0 && C0->isNullValue()) || (C1 && C1->isNullValue()))
7034 return ConstantInt::get(ReturnType, 0);
7035 break;
7036 case Intrinsic::aarch64_sve_andv:
7037 case Intrinsic::aarch64_sve_uminv:
7038 if ((C0 && C0->isNullValue()) || (C1 && C1->isAllOnesValue()))
7039 return ConstantInt::get(ReturnType, APInt::getMaxValue(Width));
7040 break;
7041 case Intrinsic::aarch64_sve_smaxv:
7042 if ((C0 && C0->isNullValue()) || (C1 && C1->isMinSignedValue()))
7043 return ConstantInt::get(ReturnType, APInt::getSignedMinValue(Width));
7044 break;
7045 case Intrinsic::aarch64_sve_sminv:
7046 if ((C0 && C0->isNullValue()) || (C1 && C1->isMaxSignedValue()))
7047 return ConstantInt::get(ReturnType, APInt::getSignedMaxValue(Width));
7048 break;
7049 }
7050
7051 switch (IID) {
7052 case Intrinsic::aarch64_sve_andv:
7053 case Intrinsic::aarch64_sve_orv:
7054 case Intrinsic::aarch64_sve_smaxv:
7055 case Intrinsic::aarch64_sve_sminv:
7056 case Intrinsic::aarch64_sve_umaxv:
7057 case Intrinsic::aarch64_sve_uminv:
7058 // sve_reduce_##(all, splat(X)) ==> X
7059 if (C0 && C0->isAllOnesValue()) {
7060 if (Value *SplatVal = getSplatValue(Op1)) {
7061 assert(SplatVal->getType() == ReturnType && "Unexpected result type!");
7062 return SplatVal;
7063 }
7064 }
7065 break;
7066 case Intrinsic::aarch64_sve_eorv:
7067 // sve_reduce_xor(all, splat(X)) ==> 0
7068 if (C0 && C0->isAllOnesValue())
7069 if (getSplatValue(Op1))
7070 return ConstantInt::get(ReturnType, 0);
7071 break;
7072 }
7073
7074 return nullptr;
7075}
7076
7078 Value *Op0, Value *Op1, FastMathFlags FMF,
7079 const SimplifyQuery &Q) {
7080 unsigned BitWidth = ReturnType->getScalarSizeInBits();
7081 switch (IID) {
7082 case Intrinsic::vector_shuffle:
7083 // A poison mask selects poison in every lane.
7084 if (isa<PoisonValue>(Op1))
7085 return PoisonValue::get(ReturnType);
7086 // The only in-range index into a one-element vector is 0, and other
7087 // indices select poison, so the shuffle is its source.
7088 if (cast<VectorType>(ReturnType)->getElementCount().isScalar())
7089 return Op0;
7090 break;
7091 case Intrinsic::get_active_lane_mask: {
7092 if (match(Op1, m_Zero()))
7093 return ConstantInt::getFalse(ReturnType);
7094
7095 const Function *F = Q.getFunction();
7096 if (!F)
7097 break;
7098
7099 auto *ScalableTy = dyn_cast<ScalableVectorType>(ReturnType);
7100 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
7101 if (ScalableTy && Attr.isValid()) {
7102 std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
7103 if (!VScaleMax)
7104 break;
7105 uint64_t MaxPossibleMaskElements =
7106 (uint64_t)ScalableTy->getMinNumElements() * (*VScaleMax);
7107
7108 const APInt *Op1Val;
7109 if (match(Op0, m_Zero()) && match(Op1, m_APInt(Op1Val)) &&
7110 Op1Val->uge(MaxPossibleMaskElements))
7111 return ConstantInt::getAllOnesValue(ReturnType);
7112 }
7113 break;
7114 }
7115 case Intrinsic::abs:
7116 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
7117 // It is always ok to pick the earlier abs. We'll just lose nsw if its only
7118 // on the outer abs.
7120 return Op0;
7121 break;
7122
7123 case Intrinsic::cttz: {
7124 Value *X;
7125 if (match(Op0, m_Shl(m_One(), m_Value(X))))
7126 return X;
7127 break;
7128 }
7129 case Intrinsic::ctlz: {
7130 Value *X;
7131 if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
7132 return X;
7133 if (match(Op0, m_AShr(m_Negative(), m_Value())))
7134 return Constant::getNullValue(ReturnType);
7135 break;
7136 }
7137 case Intrinsic::pdep: {
7138 if (match(Op0, m_Zero()))
7139 return Constant::getNullValue(ReturnType);
7140 if (match(Op1, m_Zero()))
7141 return Constant::getNullValue(ReturnType);
7142 if (match(Op1, m_AllOnes()))
7143 return Op0;
7144 break;
7145 }
7146 case Intrinsic::pext: {
7147 if (match(Op0, m_Zero()))
7148 return Constant::getNullValue(ReturnType);
7149 if (match(Op1, m_Zero()))
7150 return Constant::getNullValue(ReturnType);
7151 if (match(Op1, m_AllOnes()))
7152 return Op0;
7153 break;
7154 }
7155 case Intrinsic::ptrmask: {
7156 // NOTE: We can't apply this simplifications based on the value of Op1
7157 // because we need to preserve provenance.
7158 if (Q.isUndefValue(Op0) || match(Op0, m_Zero()))
7159 return Constant::getNullValue(Op0->getType());
7160
7162 Q.DL.getIndexTypeSizeInBits(Op0->getType()) &&
7163 "Invalid mask width");
7164 // If index-width (mask size) is less than pointer-size then mask is
7165 // 1-extended.
7166 if (match(Op1, m_PtrToIntOrAddr(m_Specific(Op0))))
7167 return Op0;
7168
7169 // NOTE: We may have attributes associated with the return value of the
7170 // llvm.ptrmask intrinsic that will be lost when we just return the
7171 // operand. We should try to preserve them.
7172 if (match(Op1, m_AllOnes()) || Q.isUndefValue(Op1))
7173 return Op0;
7174
7175 Constant *C;
7176 if (match(Op1, m_ImmConstant(C))) {
7177 KnownBits PtrKnown = computeKnownBits(Op0, Q);
7178 // See if we only masking off bits we know are already zero due to
7179 // alignment.
7180 APInt IrrelevantPtrBits =
7181 PtrKnown.Zero.zextOrTrunc(C->getType()->getScalarSizeInBits());
7183 Instruction::Or, C, ConstantInt::get(C->getType(), IrrelevantPtrBits),
7184 Q.DL);
7185 if (C != nullptr && C->isAllOnesValue())
7186 return Op0;
7187 }
7188 break;
7189 }
7190 case Intrinsic::smax:
7191 case Intrinsic::smin:
7192 case Intrinsic::umax:
7193 case Intrinsic::umin: {
7194 // If the arguments are the same, this is a no-op.
7195 if (Op0 == Op1)
7196 return Op0;
7197
7198 // Canonicalize immediate constant operand as Op1.
7199 if (match(Op0, m_ImmConstant()))
7200 std::swap(Op0, Op1);
7201
7202 // Assume undef is the limit value.
7203 if (Q.isUndefValue(Op1))
7204 return ConstantInt::get(
7206
7207 const APInt *C;
7208 if (match(Op1, m_APIntAllowPoison(C))) {
7209 // Clamp to limit value. For example:
7210 // umax(i8 %x, i8 255) --> 255
7212 return ConstantInt::get(ReturnType, *C);
7213
7214 // If the constant op is the opposite of the limit value, the other must
7215 // be larger/smaller or equal. For example:
7216 // umin(i8 %x, i8 255) --> %x
7219 return Op0;
7220
7221 // Remove nested call if constant operands allow it. Example:
7222 // max (max X, 7), 5 -> max X, 7
7223 auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
7224 if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
7225 // TODO: loosen undef/splat restrictions for vector constants.
7226 Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
7227 const APInt *InnerC;
7228 if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
7229 ICmpInst::compare(*InnerC, *C,
7232 return Op0;
7233 }
7234 }
7235
7236 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
7237 return V;
7238 if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
7239 return V;
7240
7243 if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
7244 return Op0;
7245 if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
7246 return Op1;
7247
7248 break;
7249 }
7250 case Intrinsic::scmp:
7251 case Intrinsic::ucmp: {
7252 // Fold to a constant if the relationship between operands can be
7253 // established with certainty
7254 if (isICmpTrue(CmpInst::ICMP_EQ, Op0, Op1, Q, RecursionLimit))
7255 return Constant::getNullValue(ReturnType);
7256
7257 ICmpInst::Predicate PredGT =
7258 IID == Intrinsic::scmp ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
7259 if (isICmpTrue(PredGT, Op0, Op1, Q, RecursionLimit))
7260 return ConstantInt::get(ReturnType, 1);
7261
7262 ICmpInst::Predicate PredLT =
7263 IID == Intrinsic::scmp ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
7264 if (isICmpTrue(PredLT, Op0, Op1, Q, RecursionLimit))
7265 return ConstantInt::getSigned(ReturnType, -1);
7266
7267 break;
7268 }
7269 case Intrinsic::umulh:
7270 case Intrinsic::smulh:
7271 // Multiply by one.
7272 if (IID == Intrinsic::umulh || BitWidth == 1)
7273 if (match(Op0, m_One()) || match(Op1, m_One()))
7274 return Constant::getNullValue(ReturnType);
7275 // Multiply by undef -> zero (NOT undef!) as other arg could still be
7276 // zero.
7277 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
7278 return Constant::getNullValue(ReturnType);
7279
7280 // Multiply by zero.
7281 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
7282 return Constant::getNullValue(ReturnType);
7283 break;
7284 case Intrinsic::usub_with_overflow:
7285 case Intrinsic::ssub_with_overflow:
7286 // X - X -> { 0, false }
7287 // X - undef -> { 0, false }
7288 // undef - X -> { 0, false }
7289 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
7290 return Constant::getNullValue(ReturnType);
7291 break;
7292 case Intrinsic::uadd_with_overflow:
7293 case Intrinsic::sadd_with_overflow:
7294 // X + undef -> { -1, false }
7295 // undef + x -> { -1, false }
7296 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
7297 return ConstantStruct::get(
7298 cast<StructType>(ReturnType),
7299 {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
7300 Constant::getNullValue(ReturnType->getStructElementType(1))});
7301 }
7302 break;
7303 case Intrinsic::umul_with_overflow:
7304 case Intrinsic::smul_with_overflow:
7305 // 0 * X -> { 0, false }
7306 // X * 0 -> { 0, false }
7307 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
7308 return Constant::getNullValue(ReturnType);
7309 // undef * X -> { 0, false }
7310 // X * undef -> { 0, false }
7311 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
7312 return Constant::getNullValue(ReturnType);
7313 break;
7314 case Intrinsic::uadd_sat:
7315 // sat(MAX + X) -> MAX
7316 // sat(X + MAX) -> MAX
7317 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
7318 return Constant::getAllOnesValue(ReturnType);
7319 [[fallthrough]];
7320 case Intrinsic::sadd_sat:
7321 // sat(X + undef) -> -1
7322 // sat(undef + X) -> -1
7323 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
7324 // For signed: Assume undef is ~X, in which case X + ~X = -1.
7325 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
7326 return Constant::getAllOnesValue(ReturnType);
7327
7328 // X + 0 -> X
7329 if (match(Op1, m_Zero()))
7330 return Op0;
7331 // 0 + X -> X
7332 if (match(Op0, m_Zero()))
7333 return Op1;
7334 break;
7335 case Intrinsic::usub_sat:
7336 // sat(0 - X) -> 0, sat(X - MAX) -> 0
7337 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
7338 return Constant::getNullValue(ReturnType);
7339 [[fallthrough]];
7340 case Intrinsic::ssub_sat:
7341 // X - X -> 0, X - undef -> 0, undef - X -> 0
7342 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
7343 return Constant::getNullValue(ReturnType);
7344 // X - 0 -> X
7345 if (match(Op1, m_Zero()))
7346 return Op0;
7347 break;
7348 case Intrinsic::ushl_sat:
7349 case Intrinsic::sshl_sat:
7350 if (isPoisonShift(Op1, Q))
7351 return PoisonValue::get(ReturnType);
7352 // X << 0 -> X
7353 if (match(Op1, m_Zero()))
7354 return Op0;
7355 // 0 << Y -> 0
7356 if (match(Op0, m_Zero()))
7357 return Op0;
7358 if (IID == Intrinsic::ushl_sat) {
7359 // -1 u<< Y -> -1
7360 if (match(Op0, m_AllOnes()))
7361 return Op0;
7362 } else {
7363 // SINT_MAX s<< Y -> SINT_MAX, SINT_MIN s<< Y -> SINT_MIN
7364 if (match(Op0, m_MaxSignedValue()) || match(Op0, m_SignMask()))
7365 return Op0;
7366 }
7367 break;
7368 case Intrinsic::load_relative:
7369 if (auto *C0 = dyn_cast<Constant>(Op0))
7370 if (auto *C1 = dyn_cast<Constant>(Op1))
7371 return simplifyRelativeLoad(C0, C1, Q.DL);
7372 break;
7373 case Intrinsic::powi:
7374 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
7375 // powi(x, 0) -> 1.0
7376 if (Power->isZero())
7377 return ConstantFP::get(Op0->getType(), 1.0);
7378 // powi(x, 1) -> x
7379 if (Power->isOne())
7380 return Op0;
7381 }
7382 break;
7383 case Intrinsic::ldexp:
7384 return simplifyLdexp(Op0, Op1, Q, false);
7385 case Intrinsic::fptrunc_round:
7386 // fptrunc_round ( fpext X, rm ) --> X, like fptrunc (fpext X).
7387 // Only match with the default rounding mode.
7388 if (match(Op0, m_FPExt(m_Value())))
7389 return simplifyCastInst(Instruction::FPTrunc, Op0, ReturnType, Q,
7391 break;
7392 case Intrinsic::copysign:
7393 // copysign X, X --> X
7394 if (Op0 == Op1)
7395 return Op0;
7396 // copysign -X, X --> X
7397 // copysign X, -X --> -X
7398 if (match(Op0, m_FNeg(m_Specific(Op1))) ||
7399 match(Op1, m_FNeg(m_Specific(Op0))))
7400 return Op1;
7401 break;
7402 case Intrinsic::is_fpclass: {
7403 uint64_t Mask = cast<ConstantInt>(Op1)->getZExtValue();
7404 // If all tests are made, it doesn't matter what the value is.
7405 if ((Mask & fcAllFlags) == fcAllFlags)
7406 return ConstantInt::get(ReturnType, true);
7407 if ((Mask & fcAllFlags) == 0)
7408 return ConstantInt::get(ReturnType, false);
7409 if (Q.isUndefValue(Op0))
7410 return UndefValue::get(ReturnType);
7411 break;
7412 }
7413 case Intrinsic::maxnum:
7414 case Intrinsic::minnum:
7415 case Intrinsic::maximum:
7416 case Intrinsic::minimum:
7417 case Intrinsic::maximumnum:
7418 case Intrinsic::minimumnum: {
7419 // In several cases here, we deviate from exact IEEE 754 semantics
7420 // to enable optimizations (as allowed by the LLVM IR spec).
7421 //
7422 // For instance, we may return one of the arguments unmodified instead of
7423 // inserting an llvm.canonicalize to transform input sNaNs into qNaNs,
7424 // or may assume all NaN inputs are qNaNs.
7425
7426 // If the arguments are the same, this is a no-op (ignoring NaN quieting)
7427 if (Op0 == Op1)
7428 return Op0;
7429
7430 // Canonicalize constant operand as Op1.
7431 if (isa<Constant>(Op0))
7432 std::swap(Op0, Op1);
7433
7434 if (Constant *C = dyn_cast<Constant>(Op1)) {
7436 Constant *NewConst = nullptr;
7437
7438 if (VectorType *VTy = dyn_cast<VectorType>(C->getType())) {
7439 ElementCount ElemCount = VTy->getElementCount();
7440
7441 if (Constant *SplatVal = C->getSplatValue()) {
7442 // Handle splat vectors (including scalable vectors)
7443 OptResult = OptimizeConstMinMax(SplatVal, IID, FMF, &NewConst);
7444 if (OptResult == MinMaxOptResult::UseNewConstVal)
7445 NewConst = ConstantVector::getSplat(ElemCount, NewConst);
7446
7447 } else if (ElemCount.isFixed()) {
7448 // Storage to build up new const return value (with NaNs quieted)
7450
7451 // Check elementwise whether we can optimize to either a constant
7452 // value or return the LHS value. We cannot mix and match LHS +
7453 // constant elements, as this would require inserting a new
7454 // VectorShuffle instruction, which is not allowed in simplifyBinOp.
7455 OptResult = MinMaxOptResult::UseEither;
7456 for (unsigned i = 0; i != ElemCount.getFixedValue(); ++i) {
7457 auto *Elt = C->getAggregateElement(i);
7458 if (!Elt) {
7460 break;
7461 }
7462 auto ElemResult = OptimizeConstMinMax(Elt, IID, FMF, &NewConst);
7463 if (ElemResult == MinMaxOptResult::CannotOptimize ||
7464 (ElemResult != OptResult &&
7465 OptResult != MinMaxOptResult::UseEither &&
7466 ElemResult != MinMaxOptResult::UseEither)) {
7468 break;
7469 }
7470 NewC[i] = NewConst;
7471 if (ElemResult != MinMaxOptResult::UseEither)
7472 OptResult = ElemResult;
7473 }
7474 if (OptResult == MinMaxOptResult::UseNewConstVal)
7475 NewConst = ConstantVector::get(NewC);
7476 }
7477 } else {
7478 // Handle scalar inputs
7479 OptResult = OptimizeConstMinMax(C, IID, FMF, &NewConst);
7480 }
7481
7482 if (OptResult == MinMaxOptResult::UseOtherVal ||
7483 OptResult == MinMaxOptResult::UseEither)
7484 return Op0; // Return the other arg (ignoring NaN quieting)
7485 else if (OptResult == MinMaxOptResult::UseNewConstVal)
7486 return NewConst;
7487 }
7488
7489 // Min/max of the same operation with common operand:
7490 // m(m(X, Y), X) --> m(X, Y) (4 commuted variants), also through nested m,
7491 // e.g. m(m(m(X, Y), Z), X) --> m(m(X, Y), Z).
7492 if (Value *V = foldMinimumMaximumSharedOp(IID, Op0, Op1, RecursionLimit))
7493 return V;
7494 if (Value *V = foldMinimumMaximumSharedOp(IID, Op1, Op0, RecursionLimit))
7495 return V;
7496
7497 break;
7498 }
7499 case Intrinsic::vector_extract: {
7500 // (extract_vector (insert_vector _, X, 0), 0) -> X
7501 unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
7502 Value *X = nullptr;
7504 m_Zero())) &&
7505 IdxN == 0 && X->getType() == ReturnType)
7506 return X;
7507
7508 break;
7509 }
7510
7511 case Intrinsic::aarch64_sve_andv:
7512 case Intrinsic::aarch64_sve_eorv:
7513 case Intrinsic::aarch64_sve_orv:
7514 case Intrinsic::aarch64_sve_saddv:
7515 case Intrinsic::aarch64_sve_smaxv:
7516 case Intrinsic::aarch64_sve_sminv:
7517 case Intrinsic::aarch64_sve_uaddv:
7518 case Intrinsic::aarch64_sve_umaxv:
7519 case Intrinsic::aarch64_sve_uminv:
7520 return simplifySVEIntReduction(IID, ReturnType, Op0, Op1);
7521 default:
7522 break;
7523 }
7524
7525 return nullptr;
7526}
7527
7528/// interleaveN(extractvalue(deinterleaveN(x), 0), ...,
7529/// extractvalue(deinterleaveN(x), N-1)) --> x
7531 ArrayRef<Value *> Args) {
7532 unsigned Factor = getInterleaveIntrinsicFactor(IID);
7533 if (!Factor || Factor != Args.size())
7534 return nullptr;
7535
7537 IntrinsicInst *DI = nullptr;
7538 for (unsigned Idx = 0; Idx != Factor; ++Idx) {
7539 auto *EV = dyn_cast<ExtractValueInst>(Args[Idx]);
7540 if (!EV || EV->getNumIndices() != 1 || *EV->idx_begin() != Idx)
7541 return nullptr;
7542
7543 auto *CurDI = dyn_cast<IntrinsicInst>(EV->getAggregateOperand());
7544 if (!CurDI || CurDI->getIntrinsicID() != DeinterleaveID)
7545 return nullptr;
7546
7547 if (!DI)
7548 DI = CurDI;
7549 else if (DI != CurDI)
7550 return nullptr;
7551 }
7552
7553 return DI->getArgOperand(0);
7554}
7555
7558 const SimplifyQuery &Q,
7559 fp::ExceptionBehavior ExBehavior,
7560 RoundingMode Rounding) {
7561 unsigned NumOperands = Args.size();
7564 return PoisonValue::get(ReturnType);
7565
7566 // Defer to ConstantFolding if all args are constants.
7567 if (all_of(Args, IsaPred<Constant>))
7569 IID, ArrayRef((Constant *const *)Args.data(), Args.size()),
7570 ReturnType, Q.DL, Q.getFunction()))
7571 return C;
7572
7573 // Most of the intrinsics with no operands have some kind of side effect.
7574 // Don't simplify.
7575 if (!NumOperands) {
7576 switch (IID) {
7577 case Intrinsic::vscale: {
7578 if (!Q.getFunction())
7579 return nullptr;
7581 if (const APInt *C = CR.getSingleElement())
7582 return ConstantInt::get(ReturnType, C->getZExtValue());
7583 return nullptr;
7584 }
7585 default:
7586 return nullptr;
7587 }
7588 }
7589
7590 if (Value *V = simplifyIdentityInterleave(IID, Args))
7591 return V;
7592
7593 if (NumOperands == 1)
7594 return simplifyUnaryIntrinsic(IID, Args[0], FMF, Q);
7595
7596 if (NumOperands == 2)
7597 return simplifyBinaryIntrinsic(IID, ReturnType, Args[0], Args[1], FMF, Q);
7598
7599 // Handle intrinsics with 3 or more arguments.
7600 switch (IID) {
7601 case Intrinsic::masked_load:
7602 case Intrinsic::masked_gather: {
7603 Value *MaskArg = Args[1];
7604 Value *PassthruArg = Args[2];
7605 // If the mask is all zeros or poison, the "passthru" argument is the
7606 // result.
7607 if (match(MaskArg, m_ZeroOrPoison()))
7608 return PassthruArg;
7609 return nullptr;
7610 }
7611 case Intrinsic::fshl:
7612 case Intrinsic::fshr: {
7613 Value *Op0 = Args[0], *Op1 = Args[1], *ShAmtArg = Args[2];
7614
7615 // If both operands are undef, the result is undef.
7616 if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
7617 return UndefValue::get(ReturnType);
7618
7619 // If shift amount is undef, assume it is zero.
7620 if (Q.isUndefValue(ShAmtArg))
7621 return Args[IID == Intrinsic::fshl ? 0 : 1];
7622
7623 const APInt *ShAmtC;
7624 if (match(ShAmtArg, m_APInt(ShAmtC))) {
7625 // If there's effectively no shift, return the 1st arg or 2nd arg.
7626 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
7627 const APInt ShAmt = ShAmtC->urem(BitWidth);
7628 if (ShAmt.isZero())
7629 return Args[IID == Intrinsic::fshl ? 0 : 1];
7630
7631 // fshl (lshr X, C1), (shl X, C2), C1 -> X when C1 + C2 == BW
7632 // fshr (lshr X, C1), (shl X, C2), C2 -> X when C1 + C2 == BW
7633 const APInt *C1, *C2;
7634 Value *X;
7635 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
7636 match(Op1, m_Shl(m_Specific(X), m_APInt(C2))) &&
7637 *C1 + *C2 == BitWidth && ShAmt == *(IID == Intrinsic::fshl ? C1 : C2))
7638 return X;
7639 }
7640
7641 // Rotating zero by anything is zero.
7642 if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
7643 return ConstantInt::getNullValue(ReturnType);
7644
7645 // Rotating -1 by anything is -1.
7646 if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
7647 return ConstantInt::getAllOnesValue(ReturnType);
7648
7649 return nullptr;
7650 }
7651 case Intrinsic::experimental_constrained_fma:
7652 return simplifyFPOp(Args, {}, Q, ExBehavior, Rounding);
7653 case Intrinsic::fma:
7654 case Intrinsic::fmuladd:
7655 return simplifyFPOp(Args, {}, Q, fp::ebIgnore,
7657 case Intrinsic::smul_fix:
7658 case Intrinsic::smul_fix_sat: {
7659 Value *Op0 = Args[0];
7660 Value *Op1 = Args[1];
7661 Value *Op2 = Args[2];
7662
7663 // Canonicalize constant operand as Op1 (ConstantFolding handles the case
7664 // when both Op0 and Op1 are constant so we do not care about that special
7665 // case here).
7666 if (isa<Constant>(Op0))
7667 std::swap(Op0, Op1);
7668
7669 // X * 0 -> 0
7670 if (match(Op1, m_Zero()))
7671 return Constant::getNullValue(ReturnType);
7672
7673 // X * undef -> 0
7674 if (Q.isUndefValue(Op1))
7675 return Constant::getNullValue(ReturnType);
7676
7677 // X * (1 << Scale) -> X
7678 APInt ScaledOne =
7679 APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
7680 cast<ConstantInt>(Op2)->getZExtValue());
7681 if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
7682 return Op0;
7683
7684 return nullptr;
7685 }
7686 case Intrinsic::vector_insert: {
7687 Value *Vec = Args[0];
7688 Value *SubVec = Args[1];
7689 Value *Idx = Args[2];
7690
7691 // (insert_vector Y, (extract_vector X, 0), 0) -> X
7692 // where: Y is X, or Y is undef
7693 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
7694 Value *X = nullptr;
7695 if (match(SubVec,
7697 (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
7698 X->getType() == ReturnType)
7699 return X;
7700
7701 return nullptr;
7702 }
7703 case Intrinsic::vector_splice_right: {
7704 // splice.right(splice.left(poison, x, offset), poison, offset) -> x
7705 Value *X, *Offset = Args[2];
7708 isa<PoisonValue>(Args[1]))
7709 return X;
7710 [[fallthrough]];
7711 }
7712 case Intrinsic::vector_splice_left: {
7713 Value *Offset = Args[2];
7714 auto *Ty = cast<VectorType>(ReturnType);
7715 if (Q.isUndefValue(Offset))
7716 return PoisonValue::get(Ty);
7717
7718 unsigned BitWidth = Offset->getType()->getScalarSizeInBits();
7719 ConstantRange NumElts(
7720 APInt(BitWidth, Ty->getElementCount().getKnownMinValue()));
7721 if (Ty->isScalableTy())
7722 NumElts = NumElts.multiply(Q.getFunction()
7724 : ConstantRange::getFull(BitWidth));
7725
7726 // If we know Offset > NumElts, simplify to poison.
7728 if (CR.getUnsignedMin().ugt(NumElts.getUnsignedMax()))
7729 return PoisonValue::get(Ty);
7730
7731 // splice.left(a, b, 0) --> a, splice.right(a, b, 0) --> b
7732 if (CR.isSingleElement() && CR.getSingleElement()->isZero())
7733 return IID == Intrinsic::vector_splice_left ? Args[0] : Args[1];
7734
7735 return nullptr;
7736 }
7737 case Intrinsic::experimental_constrained_fadd:
7738 return simplifyFAddInst(Args[0], Args[1], FMF, Q, ExBehavior, Rounding);
7739 case Intrinsic::experimental_constrained_fsub:
7740 return simplifyFSubInst(Args[0], Args[1], FMF, Q, ExBehavior, Rounding);
7741 case Intrinsic::experimental_constrained_fmul:
7742 return simplifyFMulInst(Args[0], Args[1], FMF, Q, ExBehavior, Rounding);
7743 case Intrinsic::experimental_constrained_fdiv:
7744 return simplifyFDivInst(Args[0], Args[1], FMF, Q, ExBehavior, Rounding);
7745 case Intrinsic::experimental_constrained_frem:
7746 return simplifyFRemInst(Args[0], Args[1], FMF, Q, ExBehavior, Rounding);
7747 case Intrinsic::experimental_constrained_ldexp:
7748 return simplifyLdexp(Args[0], Args[1], Q, true);
7749 case Intrinsic::experimental_vp_reverse: {
7750 Value *Vec = Args[0];
7751 Value *EVL = Args[2];
7752
7753 Value *X;
7754 // vp.reverse(vp.reverse(X)) == X (mask doesn't matter)
7756 m_Value(X), m_Value(), m_Specific(EVL))))
7757 return X;
7758
7759 // vp.reverse(splat(X)) -> splat(X) (regardless of mask and EVL)
7760 if (isSplatValue(Vec))
7761 return Vec;
7762 return nullptr;
7763 }
7764 default:
7765 return nullptr;
7766 }
7767}
7768
7770 const SimplifyQuery &Q) {
7771 // Operand bundles should not be in Args.
7772 assert(Call->arg_size() == Args.size());
7773 Intrinsic::ID IID = Call->getCalledFunction()->getIntrinsicID();
7774 Type *ReturnType = Call->getCalledFunction()->getReturnType();
7775
7776 switch (IID) {
7777 case Intrinsic::experimental_gc_relocate: {
7779 Value *DerivedPtr = GCR.getDerivedPtr();
7780 Value *BasePtr = GCR.getBasePtr();
7781
7782 // Undef is undef, even after relocation.
7783 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
7784 return UndefValue::get(GCR.getType());
7785 }
7786
7787 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
7788 // For now, the assumption is that the relocation of null will be null
7789 // for most any collector. If this ever changes, a corresponding hook
7790 // should be added to GCStrategy and this code should check it first.
7791 if (isa<ConstantPointerNull>(DerivedPtr)) {
7792 // Use null-pointer of gc_relocate's type to replace it.
7793 return ConstantPointerNull::get(PT);
7794 }
7795 }
7796 return nullptr;
7797 }
7798 default: {
7799 // Use the default FP environment if none is found.
7802 if (auto *Constrained = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
7803 ExBehavior = Constrained->getExceptionBehavior().value_or(ExBehavior);
7804 Rounding = Constrained->getRoundingMode().value_or(Rounding);
7805 }
7806 return simplifyIntrinsic(
7807 IID, ReturnType, Args, Call->getFastMathFlagsOrNone(),
7808 Q.getWithFunction(Call->getFunction()), ExBehavior, Rounding);
7809 }
7810 }
7811}
7812
7814 const SimplifyQuery &Q) {
7815 auto *F = Call->getCalledFunction();
7816 if (!F)
7817 return nullptr;
7818
7819 // Check for constant arguments before querying canConstantFoldCallTo.
7820 // Checking arguments is cheaper than TLI classification and attribute checks.
7821 SmallVector<Constant *, 4> ConstantArgs;
7822 ConstantArgs.reserve(Args.size());
7823 for (Value *Arg : Args) {
7825 if (!C) {
7826 if (isa<MetadataAsValue>(Arg))
7827 continue;
7828 return nullptr;
7829 }
7830 ConstantArgs.push_back(C);
7831 }
7832
7833 // Check if this is a known library function that we know how to fold.
7834 if (!canConstantFoldCallTo(Call, F, Q.TLI))
7835 return nullptr;
7836
7837 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
7838}
7839
7841 const SimplifyQuery &Q) {
7842 // Args should not contain operand bundle operands.
7843 assert(Call->arg_size() == Args.size());
7844
7845 // musttail calls can only be simplified if they are also DCEd.
7846 // As we can't guarantee this here, don't simplify them.
7847 if (Call->isMustTailCall())
7848 return nullptr;
7849
7850 // call undef -> poison
7851 // call null -> poison
7852 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
7853 return PoisonValue::get(Call->getType());
7854
7855 if (Value *V = tryConstantFoldCall(Call, Args, Q))
7856 return V;
7857
7858 auto *F = dyn_cast<Function>(Callee);
7859 if (F && F->isIntrinsic())
7860 if (Value *Ret = ::simplifyIntrinsic(Call, Args, Q))
7861 return Ret;
7862
7863 return nullptr;
7864}
7865
7868 SmallVector<Value *, 4> Args(Call->args());
7869 if (Value *V = tryConstantFoldCall(Call, Args, Q))
7870 return V;
7871 if (Value *Ret = ::simplifyIntrinsic(Call, Args, Q))
7872 return Ret;
7873 return nullptr;
7874}
7875
7876/// Given operands for a Freeze, see if we can fold the result.
7878 // Use a utility function defined in ValueTracking.
7880 return Op0;
7881 // We have room for improvement.
7882 return nullptr;
7883}
7884
7886 return ::simplifyFreezeInst(Op0, Q);
7887}
7888
7890 const SimplifyQuery &Q) {
7891 if (LI->isVolatile())
7892 return nullptr;
7893
7894 if (auto *PtrOpC = dyn_cast<Constant>(PtrOp))
7895 return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Q.DL);
7896
7897 // We can only fold the load if it is from a constant global with definitive
7898 // initializer. Skip expensive logic if this is not the case.
7900 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7901 return nullptr;
7902
7903 // If GlobalVariable's initializer is uniform, then return the constant
7904 // regardless of its offset.
7905 if (Constant *C = ConstantFoldLoadFromUniformValue(GV->getInitializer(),
7906 LI->getType(), Q.DL))
7907 return C;
7908
7909 // Try to convert operand into a constant by stripping offsets while looking
7910 // through invariant.group intrinsics.
7912 PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
7913 Q.DL, Offset, /* AllowNonInbounts */ true,
7914 /* AllowInvariantGroup */ true);
7915 if (PtrOp == GV) {
7916 // Index size may have changed due to address space casts.
7917 Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
7918 return ConstantFoldLoadFromConstPtr(GV, LI->getType(), std::move(Offset),
7919 Q.DL);
7920 }
7921
7922 return nullptr;
7923}
7924
7925/// See if we can compute a simplified version of this instruction.
7926/// If not, this returns null.
7927
7929 Instruction *I, ArrayRef<Value *> NewOps, const SimplifyQuery &SQ,
7930 SmallVectorImpl<Instruction *> *DropAnnotations, unsigned MaxRecurse) {
7931 assert(I->getFunction() && "instruction should be inserted in a function");
7932 assert((!SQ.getFunction() || SQ.getFunction() == I->getFunction()) &&
7933 "context instruction should be in the same function");
7934
7935 const SimplifyQuery Q = SQ.CtxI ? SQ : SQ.getWithInstruction(I);
7936
7937 switch (I->getOpcode()) {
7938 default:
7939 if (all_of(NewOps, IsaPred<Constant>)) {
7940 SmallVector<Constant *, 8> NewConstOps(NewOps.size());
7941 transform(NewOps, NewConstOps.begin(),
7942 [](Value *V) { return cast<Constant>(V); });
7943 return ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
7944 }
7945 return nullptr;
7946 case Instruction::FNeg:
7947 return simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q, MaxRecurse);
7948 case Instruction::FAdd:
7949 return simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7950 MaxRecurse);
7951 case Instruction::Add:
7952 return simplifyAddInst(
7953 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7954 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7955 case Instruction::FSub:
7956 return simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7957 MaxRecurse);
7958 case Instruction::Sub:
7959 return simplifySubInst(
7960 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7961 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7962 case Instruction::FMul:
7963 return simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7964 MaxRecurse);
7965 case Instruction::Mul:
7966 return simplifyMulInst(
7967 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7968 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7969 case Instruction::SDiv:
7970 return simplifySDivInst(NewOps[0], NewOps[1],
7972 MaxRecurse);
7973 case Instruction::UDiv:
7974 return simplifyUDivInst(NewOps[0], NewOps[1],
7976 MaxRecurse);
7977 case Instruction::FDiv:
7978 return simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7979 MaxRecurse);
7980 case Instruction::SRem:
7981 return simplifySRemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7982 case Instruction::URem:
7983 return simplifyURemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7984 case Instruction::FRem:
7985 return simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
7986 MaxRecurse);
7987 case Instruction::Shl:
7988 return simplifyShlInst(
7989 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
7990 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
7991 case Instruction::LShr:
7992 return simplifyLShrInst(NewOps[0], NewOps[1],
7994 MaxRecurse);
7995 case Instruction::AShr:
7996 return simplifyAShrInst(NewOps[0], NewOps[1],
7998 MaxRecurse);
7999 case Instruction::And:
8000 return simplifyAndInst(NewOps[0], NewOps[1], Q, MaxRecurse);
8001 case Instruction::Or:
8002 return simplifyOrInst(NewOps[0], NewOps[1], Q, MaxRecurse);
8003 case Instruction::Xor:
8004 return simplifyXorInst(NewOps[0], NewOps[1], Q, MaxRecurse);
8005 case Instruction::ICmp:
8006 return simplifyICmpInst(cast<ICmpInst>(I)->getCmpPredicate(), NewOps[0],
8007 NewOps[1], Q, MaxRecurse);
8008 case Instruction::FCmp:
8009 return simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
8010 NewOps[1], I->getFastMathFlags(), Q, MaxRecurse);
8011 case Instruction::Select: {
8012 FastMathFlags FMF;
8013 if (auto *FPMO = dyn_cast<FPMathOperator>(I))
8014 FMF = FPMO->getFastMathFlags();
8015 return simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], FMF, Q,
8016 DropAnnotations, MaxRecurse);
8017 }
8018 case Instruction::GetElementPtr: {
8019 auto *GEPI = cast<GetElementPtrInst>(I);
8020 return simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
8021 ArrayRef(NewOps).slice(1), GEPI->getNoWrapFlags(), Q,
8022 MaxRecurse);
8023 }
8024 case Instruction::InsertValue: {
8026 return simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q,
8027 MaxRecurse);
8028 }
8029 case Instruction::InsertElement:
8030 return simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
8031 case Instruction::ExtractValue: {
8032 auto *EVI = cast<ExtractValueInst>(I);
8033 return simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q,
8034 MaxRecurse);
8035 }
8036 case Instruction::ExtractElement:
8037 return simplifyExtractElementInst(NewOps[0], NewOps[1], Q, MaxRecurse);
8038 case Instruction::BitInsert:
8039 return simplifyBitInsertInst(NewOps[0], NewOps[1], NewOps[2], Q,
8040 MaxRecurse);
8041 case Instruction::BitExtract:
8042 return simplifyBitExtractInst(I->getType(), NewOps[0], NewOps[1], Q,
8043 MaxRecurse);
8044 case Instruction::ShuffleVector: {
8045 auto *SVI = cast<ShuffleVectorInst>(I);
8046 return simplifyShuffleVectorInst(NewOps[0], NewOps[1],
8047 SVI->getShuffleMask(), SVI->getType(), Q,
8048 MaxRecurse);
8049 }
8050 case Instruction::PHI:
8051 return simplifyPHINode(cast<PHINode>(I), NewOps, Q);
8052 case Instruction::Call:
8053 return simplifyCall(
8054 cast<CallInst>(I), NewOps.back(),
8055 NewOps.drop_back(1 + cast<CallInst>(I)->getNumTotalBundleOperands()),
8056 Q);
8057 case Instruction::Freeze:
8058 return llvm::simplifyFreezeInst(NewOps[0], Q);
8059#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
8060#include "llvm/IR/Instruction.def"
8061#undef HANDLE_CAST_INST
8062 if (I->getOpcode() == Instruction::AddrSpaceCast) {
8064 NewOps[0], I->getType(),
8065 Q.IIQ.UseInstrInfo && cast<AddrSpaceCastInst>(I)->hasNonNull(), Q,
8066 MaxRecurse);
8067 }
8068
8069 return simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q,
8070 MaxRecurse);
8071 case Instruction::Alloca:
8072 // No simplifications for Alloca and it can't be constant folded.
8073 return nullptr;
8074 case Instruction::Load:
8075 return simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
8076 }
8077}
8078
8080 ArrayRef<Value *> NewOps,
8081 const SimplifyQuery &SQ) {
8082 assert(NewOps.size() == I->getNumOperands() &&
8083 "Number of operands should match the instruction!");
8084 return ::simplifyInstructionWithOperands(
8085 I, NewOps, SQ, /*DropAnnotations=*/nullptr, RecursionLimit);
8086}
8087
8088Value *
8090 SmallVectorImpl<Instruction *> *DropAnnotations) {
8091 SmallVector<Value *, 8> Ops(I->operands());
8092 Value *Result = ::simplifyInstructionWithOperands(I, Ops, SQ, DropAnnotations,
8094
8095 /// If called on unreachable code, the instruction may simplify to itself.
8096 /// Make life easier for users by detecting that case here, and returning a
8097 /// safe value instead.
8098 return Result == I ? PoisonValue::get(I->getType()) : Result;
8099}
8100
8101/// Implementation of recursive simplification through an instruction's
8102/// uses.
8103///
8104/// This is the common implementation of the recursive simplification routines.
8105/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
8106/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
8107/// instructions to process and attempt to simplify it using
8108/// InstructionSimplify. Recursively visited users which could not be
8109/// simplified themselves are to the optional UnsimplifiedUsers set for
8110/// further processing by the caller.
8111///
8112/// This routine returns 'true' only when *it* simplifies something. The passed
8113/// in simplified value does not count toward this.
8115 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
8116 const DominatorTree *DT, AssumptionCache *AC,
8117 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
8118 bool Simplified = false;
8120 const DataLayout &DL = I->getDataLayout();
8121
8122 // If we have an explicit value to collapse to, do that round of the
8123 // simplification loop by hand initially.
8124 if (SimpleV) {
8125 for (Instruction *U : I->users())
8126 if (U != I)
8127 Worklist.insert(U);
8128
8129 // Replace the instruction with its simplified value.
8130 I->replaceAllUsesWith(SimpleV);
8131
8132 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
8133 I->eraseFromParent();
8134 } else {
8135 Worklist.insert(I);
8136 }
8137
8138 // Note that we must test the size on each iteration, the worklist can grow.
8139 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
8140 I = Worklist[Idx];
8141
8142 // See if this instruction simplifies.
8143 SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
8144 if (!SimpleV) {
8145 if (UnsimplifiedUsers)
8146 UnsimplifiedUsers->insert(I);
8147 continue;
8148 }
8149
8150 Simplified = true;
8151
8152 // Stash away all the uses of the old instruction so we can check them for
8153 // recursive simplifications after a RAUW. This is cheaper than checking all
8154 // uses of To on the recursive step in most cases.
8155 for (Instruction *U : I->users())
8156 Worklist.insert(U);
8157
8158 // Replace the instruction with its simplified value.
8159 I->replaceAllUsesWith(SimpleV);
8160
8161 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
8162 I->eraseFromParent();
8163 }
8164 return Simplified;
8165}
8166
8168 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
8169 const DominatorTree *DT, AssumptionCache *AC,
8170 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
8171 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
8172 assert(SimpleV && "Must provide a simplified value.");
8173 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
8174 UnsimplifiedUsers);
8175}
8176
8177namespace llvm {
8179 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
8180 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
8181 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8182 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
8183 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
8184 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
8185 return {F.getDataLayout(), TLI, DT, AC};
8186}
8187
8189 const DataLayout &DL) {
8190 return {DL, &AR.TLI, &AR.DT, &AR.AC};
8191}
8192
8193template <class T, class... TArgs>
8195 Function &F) {
8196 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
8197 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
8198 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
8199 return {F.getDataLayout(), TLI, DT, AC};
8200}
8202 Function &);
8203
8205 if (!CanUseUndef)
8206 return false;
8207
8208 return match(V, m_Undef());
8209}
8210
8211} // namespace llvm
8212
8213void InstSimplifyFolder::anchor() {}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
IRTranslator LLVM IR MI
static Value * simplifyCmpSelFalseCase(CmpPredicate Pred, Value *LHS, Value *RHS, Value *Cond, const SimplifyQuery &Q, unsigned MaxRecurse)
Simplify comparison with false branch of select.
static Value * simplifyCmpSelCase(CmpPredicate Pred, Value *LHS, Value *RHS, Value *Cond, const SimplifyQuery &Q, unsigned MaxRecurse, Constant *TrueOrFalse)
Simplify comparison with true or false branch of select: sel = select i1 cond, i32 tv,...
static Value * foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1)
Given a min/max intrinsic, see if it can be removed based on having an operand that is another min/ma...
static Value * expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L, Value *R, Instruction::BinaryOps OpcodeToExpand, const SimplifyQuery &Q, unsigned MaxRecurse)
Try to simplify binops of form "A op (B op' C)" or the commuted variant by distributing op over op'.
static Constant * foldOrCommuteConstant(Instruction::BinaryOps Opcode, Value *&Op0, Value *&Op1, const SimplifyQuery &Q)
static bool haveNonOverlappingStorage(const Value *V1, const Value *V2)
Return true if V1 and V2 are each the base of some distict storage region [V, object_size(V)] which d...
static Constant * foldConstant(Instruction::UnaryOps Opcode, Value *&Op, const SimplifyQuery &Q)
static Value * handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp, Value *Cond, const SimplifyQuery &Q, unsigned MaxRecurse)
We know comparison with both branches of select can be simplified, but they are not equal.
static Value * threadCmpOverPHI(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
In the case of a comparison with a PHI instruction, try to simplify the comparison by seeing whether ...
static Constant * propagateNaN(Constant *In)
Try to propagate existing NaN values when possible.
static Value * simplifyICmpOfBools(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Fold an icmp when its operands have i1 scalar type.
static Value * simplifyICmpWithBinOpOnLHS(CmpPredicate Pred, BinaryOperator *LBO, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
static void getUnsignedMonotonicValues(SmallPtrSetImpl< Value * > &Res, Value *V, MonotonicType Type, const SimplifyQuery &Q, unsigned Depth=0)
Get values V_i such that V uge V_i (GreaterEq) or V ule V_i (LowerEq).
static Value * simplifyRelativeLoad(Constant *Ptr, Constant *Offset, const DataLayout &DL)
static Value * simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q, unsigned MaxRecurse)
These are simplifications common to SDiv and UDiv.
static Value * simplifyPHINode(PHINode *PN, ArrayRef< Value * > IncomingValues, const SimplifyQuery &Q)
See if we can fold the given phi. If not, returns null.
@ RecursionLimit
static bool isSameCompare(Value *V, CmpPredicate Pred, Value *LHS, Value *RHS)
isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
static Value * simplifyAndCommutative(Value *Op0, Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse)
static bool isIdempotent(Intrinsic::ID ID)
static std::optional< ConstantRange > getRange(Value *V, const InstrInfoQuery &IIQ)
Helper method to get range from metadata or attribute.
static Value * simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations, unsigned MaxRecurse)
Try to simplify a select instruction when its condition operand is an integer comparison.
static Value * simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp, ICmpInst *UnsignedICmp, bool IsAnd, const SimplifyQuery &Q)
Commuted variants are assumed to be handled by calling this function again with the parameters swappe...
static Value * simplifyWithOpsReplaced(Value *V, ArrayRef< std::pair< Value *, Value * > > Ops, const SimplifyQuery &Q, bool AllowRefinement, SmallVectorImpl< Instruction * > *DropFlags, unsigned MaxRecurse)
static bool isPoisonBitRange(Value *Offset, Type *Ty, Type *SrcTy, const SimplifyQuery &Q)
Return true if accessing the bit range of type Ty at Offset in a value of type SrcTy is poison.
static Value * simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, const InstrInfoQuery &IIQ)
static Value * simplifyAndOrOfFCmpsWithConstants(FCmpInst *Cmp0, FCmpInst *Cmp1, bool IsAnd)
Test if a pair of compares with a shared operand and 2 constants has an empty set intersection,...
static Value * simplifyICmpWithMinMax(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
simplify integer comparisons where at least one operand of the compare matches an integer min/max idi...
static Value * simplifyCmpSelTrueCase(CmpPredicate Pred, Value *LHS, Value *RHS, Value *Cond, const SimplifyQuery &Q, unsigned MaxRecurse)
Simplify comparison with true branch of select.
static Value * simplifyICmpUsingMonotonicValues(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
static bool isDereferenceableArg(const Value *V)
static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q)
Returns true if a shift by Amount always yields poison.
static Value * foldMinimumMaximumSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1, unsigned MaxRecurse)
Given a min/max intrinsic, see if it can be removed based on having an operand that is another min/ma...
static Value * simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q, unsigned MaxRecurse)
Given operands for an LShr or AShr, see if we can fold the result.
static Value * simplifyICmpWithIntrinsicOnLHS(CmpPredicate Pred, Value *LHS, Value *RHS)
static Value * simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse)
Test if there is a dominating equivalence condition for the two operands.
static Value * simplifyFPUnOp(unsigned, Value *, const FastMathFlags &, const SimplifyQuery &, unsigned)
Given the operand for a UnaryOperator, see if we can fold the result.
static Value * simplifyICmpWithBinOp(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
TODO: A large part of this logic is duplicated in InstCombine's foldICmpBinOp().
static Value * simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1, const SimplifyQuery &Q)
static Value * expandBinOp(Instruction::BinaryOps Opcode, Value *V, Value *OtherOp, Instruction::BinaryOps OpcodeToExpand, const SimplifyQuery &Q, unsigned MaxRecurse)
Try to simplify a binary operator of form "V op OtherOp" where V is "(B0 opex B1)" by distributing 'o...
static bool matchEquivZeroRHS(CmpPredicate &Pred, const Value *RHS)
Check if RHS is zero or can be transformed to an equivalent zero comparison.
static Value * simplifyICmpWithZero(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Try hard to fold icmp with zero RHS because this is a common case.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
static MinMaxOptResult OptimizeConstMinMax(const Constant *RHSConst, const Intrinsic::ID IID, FastMathFlags FMF, Constant **OutNewConstVal)
static Value * simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse)
Check for common or similar folds of integer division or integer remainder.
static bool removesFPFraction(Intrinsic::ID ID)
Return true if the intrinsic rounds a floating-point value to an integral floating-point value (not a...
static Value * simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, const InstrInfoQuery &IIQ)
static Value * simplifyIdentityInterleave(Intrinsic::ID IID, ArrayRef< Value * > Args)
interleaveN(extractvalue(deinterleaveN(x), 0), ..., extractvalue(deinterleaveN(x),...
static bool trySimplifyICmpWithAdds(CmpPredicate Pred, Value *LHS, Value *RHS, const InstrInfoQuery &IIQ)
static Value * simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, const APInt *Y, bool TrueWhenUnset)
Try to simplify a select instruction when its condition operand is an integer comparison where one op...
static Value * simplifyAssociativeBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
Generic simplifications for associative binary operations.
static Value * threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
In the case of a binary operation with an operand that is a PHI instruction, try to simplify the bino...
static Value * simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS, CmpPredicate Pred, Value *TVal, Value *FVal)
static Value * simplifySelectWithEquivalence(ArrayRef< std::pair< Value *, Value * > > Replacements, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations, unsigned MaxRecurse)
Try to simplify a select instruction when its condition operand is an integer equality or floating-po...
static bool isByValArg(const Value *V)
static Value * simplifyUnaryIntrinsic(Intrinsic::ID IID, Value *Op0, FastMathFlags FMF, const SimplifyQuery &Q)
static Constant * simplifyFPOp(ArrayRef< Value * > Ops, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior, RoundingMode Rounding)
Perform folds that are common to any floating-point operation.
static Value * threadCmpOverSelect(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
In the case of a comparison with a select instruction, try to simplify the comparison by seeing wheth...
static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Implementation of recursive simplification through an instruction's uses.
static bool isAllocDisjoint(const Value *V)
Return true if the underlying object (storage) must be disjoint from storage returned by any noalias ...
static Constant * getTrue(Type *Ty)
For a boolean type or a vector of boolean type, return true or a vector with every element true.
static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q, unsigned MaxRecurse, bool IsSigned)
Return true if we can simplify X / Y to 0.
static Value * simplifyLdexp(Value *Op0, Value *Op1, const SimplifyQuery &Q, bool IsStrict)
static Value * simplifyLogicOfAddSub(Value *Op0, Value *Op1, Instruction::BinaryOps Opcode)
Given a bitwise logic op, check if the operands are add/sub with a common source value and inverted c...
static Value * simplifySelectWithBitTest(Value *CondVal, Value *TrueVal, Value *FalseVal)
An alternative way to test if a bit is set or not.
static Value * simplifyOrLogic(Value *X, Value *Y)
static Type * getCompareTy(Value *Op)
static Value * simplifySelectWithFCmp(Value *Cond, Value *T, Value *F, FastMathFlags FMF, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations, unsigned MaxRecurse)
Try to simplify a select instruction when its condition operand is a floating-point comparison.
static Value * simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1, const SimplifyQuery &Q)
static bool isICmpTrue(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
Given a predicate and two operands, return true if the comparison is true.
static Value * tryConstantFoldCall(CallBase *Call, ArrayRef< Value * > Args, const SimplifyQuery &Q)
static Value * simplifyBinaryIntrinsic(Intrinsic::ID IID, Type *ReturnType, Value *Op0, Value *Op1, FastMathFlags FMF, const SimplifyQuery &Q)
bool isSelectWithIdenticalPHI(PHINode &PN, PHINode &IdenticalPN)
Look for the following pattern and simplify to_fold to identicalPhi.
static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V)
Compute the base pointer and cumulative constant offsets for V.
static Value * foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, int MaskVal, Value *RootVec, unsigned MaxRecurse)
For the given destination element of a shuffle, peek through shuffles to match a root vector source o...
static Value * simplifyAndOrOfFCmps(const SimplifyQuery &Q, FCmpInst *LHS, FCmpInst *RHS, bool IsAnd)
static Value * simplifyICmpWithConstant(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
static Value * extractEquivalentCondition(Value *V, CmpPredicate Pred, Value *LHS, Value *RHS)
Rummage around inside V looking for something equivalent to the comparison "LHS Pred RHS".
static Value * simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0, Value *Op1, bool IsAnd)
static Value * threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse)
In the case of a binary operation with a select instruction as an operand, try to simplify the binop ...
static Constant * computePointerDifference(const DataLayout &DL, Value *LHS, Value *RHS)
Compute the constant difference between two pointer values.
static Value * simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd)
Test if a pair of compares with a shared operand and 2 constants has an empty set intersection,...
static Value * simplifyAndOrWithICmpEq(unsigned Opcode, Value *Op0, Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse)
static Value * simplifyICmpWithDominatingAssume(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
static Value * simplifyShift(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, bool IsNSW, const SimplifyQuery &Q, unsigned MaxRecurse)
Given operands for an Shl, LShr or AShr, see if we can fold the result.
static Value * simplifySVEIntReduction(Intrinsic::ID IID, Type *ReturnType, Value *Op0, Value *Op1)
static Constant * computePointerICmp(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
static Value * simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse)
These are simplifications common to SRem and URem.
static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT)
Does the given value dominate the specified phi node?
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
int64_t C1
int64_t C0
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
bool isNegative() const
Definition APFloat.h:1616
APFloat makeQuiet() const
Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
Definition APFloat.h:1453
bool isNaN() const
Definition APFloat.h:1614
bool isSignaling() const
Definition APFloat.h:1618
bool isLargest() const
Definition APFloat.h:1632
bool isInfinity() const
Definition APFloat.h:1613
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1360
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
bool isMask(unsigned numBits) const
Definition APInt.h:484
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
an instruction to allocate memory on the stack
A container for analyses that lazily runs them and caches their results.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T * data() const
Definition ArrayRef.h:138
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
An immutable pass that tracks lazily created AssumptionCache objects.
AssumptionCache & getAssumptionCache(Function &F)
Get the cached assumptions for a function.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static LLVM_ABI bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1477
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
static ConstantFP * getNegativeZero(Type *Ty)
Definition Constants.h:458
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:62
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNaN() const
Return true if this is a floating-point NaN constant or a vector floating-point constant with all NaN...
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:520
IntegerType * getAddressType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of an address in AddressSpace.
Definition DataLayout.h:692
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Definition DataLayout.h:511
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:793
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
DominatorTree & getDomTree()
Definition Dominators.h:285
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool noNaNs() const
Definition FMF.h:65
Represents calls to the gc.relocate intrinsic.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
Represents flags for the getelementptr instruction/expression.
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
LLVM_ABI bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownAlwaysNaN() const
Return true if it's known this must always be a nan.
static constexpr FPClassTest OrderedLessThanZeroMask
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Metadata node.
Definition Metadata.h:1087
static APInt getSaturationPoint(Intrinsic::ID ID, unsigned numBits)
Min/max intrinsics are monotonic, they operate on a fixed-bitwidth values, so there is a certain thre...
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getTrueValue() const
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void truncate(size_type N)
Like resize, but requires that N is less than size().
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
This class represents zero extension of integer types.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_BitReverse(const Opnd0 &Op0)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul, true > m_c_FMul(const LHS &L, const RHS &R)
Matches FMul with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
FNeg_match< OpTy, false > m_FNeg(const OpTy &X)
Match fneg X only.
cstfp_pred_ty< is_inf > m_Inf()
Match a positive or negative infinity FP constant.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< cstfp_pred_ty< is_any_zero_fp >, RHS, Instruction::FSub > m_FNegNSZ(const RHS &X)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
ap_match< APFloat > m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
cstfp_pred_ty< is_neg_zero_fp > m_NegZeroFP()
Match a floating-point negative zero.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
auto m_Constant()
Match an arbitrary Constant and ignore it.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
auto m_FMinNum_or_FMinimumNum(const Opnd0 &Op0, const Opnd1 &Op1)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
cst_pred_ty< is_maxsignedvalue > m_MaxSignedValue()
Match an integer or vector with values having all bits except for the high bit set (0x7f....
auto m_FAbs(const Opnd0 &Op0)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Exact_match< T > m_Exact(const T &SubPattern)
BinaryOp_match< LHS, RHS, Instruction::FAdd, true > m_c_FAdd(const LHS &L, const RHS &R)
Matches FAdd with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
cstfp_pred_ty< is_nan > m_NaN()
Match an arbitrary NaN constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
TwoOps_match< Src_t, Off_t, Instruction::BitExtract > m_BitExtract(const Src_t &Src, const Off_t &Off)
Matches BitExtractInst.
ThreeOps_match< Base_t, Val_t, Off_t, Instruction::BitInsert > m_BitInsert(const Base_t &Base, const Val_t &Val, const Off_t &Off)
Matches BitInsertInst.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
auto m_FMaxNum_or_FMaximumNum(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI Value * simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a AShr, fold the result or return nulll.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Value * simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FMul, fold the result or return null.
LLVM_ABI Value * simplifyBitInsertInst(Value *Base, Value *Val, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitInsertInst, fold the result or return null.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI Value * simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef< Value * > Indices, GEPNoWrapFlags NW, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyFreezeInst(Value *Op, const SimplifyQuery &Q)
Given an operand for a Freeze, see if we can fold the result.
LLVM_ABI Constant * ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL, const Instruction *I, bool AllowNonDeterministic=true)
Attempt to constant fold a floating point binary operation with the specified operands,...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
LLVM_ABI Value * simplifyAddrSpaceCastInst(Value *Op, Type *Ty, bool IsNonNull, const SimplifyQuery &Q)
Given operands for an AddrSpaceCastInst, fold the result or return null.
LLVM_ABI Value * simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q)
Given operand for a UnaryOperator, fold the result or return null.
bool isDefaultFPEnvironment(fp::ExceptionBehavior EB, RoundingMode RM)
Returns true if the exception handling behavior and rounding mode match what is used in the default f...
Definition FPEnv.h:68
LLVM_ABI Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
LLVM_ABI Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Constant * ConstantFoldBitInsertOperands(Constant *Base, Constant *Val, Constant *Offset, const DataLayout &DL)
Attempt to constant fold a bitinsert instruction with the specified operands.
bool canRoundingModeBe(RoundingMode RM, RoundingMode QRM)
Returns true if the rounding mode RM may be QRM at compile time or at run time.
Definition FPEnv.h:80
LLVM_ABI Value * simplifyIntrinsic(Intrinsic::ID IID, Type *ReturnType, ArrayRef< Value * > Args, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an intrinsic, fold the result or return null.
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, std::optional< ConstantRange > InRange, ArrayRef< Value * > Idxs)
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
LLVM_ABI Value * simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef< int > Mask, Type *RetTy, const SimplifyQuery &Q)
Given operands for a ShuffleVectorInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI Value * simplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an Or, fold the result or return null.
LLVM_ABI Value * simplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an Xor, fold the result or return null.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
LLVM_ABI Constant * ConstantFoldIntrinsic(Intrinsic::ID ID, ArrayRef< Constant * > Ops, Type *Ty, const DataLayout &DL, const Function *CtxF=nullptr)
LLVM_ABI Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
unsigned M1(unsigned Val)
Definition VE.h:394
LLVM_ABI Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool isAllocLikeFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
SelectPatternFlavor
Specific patterns of select instructions we can match.
LLVM_ABI Value * simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Shl, fold the result or return null.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI Value * simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
LLVM_ABI Value * simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FSub, fold the result or return null.
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:947
LLVM_ABI Value * simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, FastMathFlags FMF, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
Given operands for a SelectInst, fold the result or return null.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI Value * simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FRem, fold the result or return null.
LLVM_ABI Value * simplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FAdd, fold the result or return null.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI Value * simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a LShr, fold the result or return null.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Value * simplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an And, fold the result or return null.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ABI Value * simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an InsertValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI Value * simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FDiv, fold the result or return null.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
LLVM_ABI Value * simplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for the multiplication of a FMA, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBitExtractOperands(Type *Ty, Constant *Src, Constant *Offset, const DataLayout &DL)
Attempt to constant fold a bitextract instruction with the specified result type and operands.
LLVM_ABI Value * simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q)
Given a constrained FP intrinsic call, tries to compute its simplified version.
LLVM_ABI Value * simplifyBitExtractInst(Type *Ty, Value *Src, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitExtractInst, fold the result or return null.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
LLVM_ABI std::optional< DecomposedBitTest > decomposeBitTest(Value *Cond, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
LLVM_ABI Value * simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for a UDiv, fold the result or return null.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
RoundingMode
Rounding mode.
@ NearestTiesToEven
roundTiesToEven.
@ TowardNegative
roundTowardNegative.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Value * simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, const SimplifyQuery &Q)
Given operands for an InsertElement, fold the result or return null.
constexpr unsigned BitWidth
LLVM_ABI Value * simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, const SimplifyQuery &Q, bool AllowRefinement, SmallVectorImpl< Instruction * > *DropFlags=nullptr)
See if V simplifies when its operand Op is replaced with RepOp.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Value * simplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an SRem, fold the result or return null.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
@ Continue
Definition DWP.h:26
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
std::pair< Value *, FPClassTest > fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool isCheckForZeroAndMulWithOverflow(Value *Op0, Value *Op1, bool IsAnd, Use *&Y)
Match one of the patterns up to the select/logic op: Op0 = icmp ne i4 X, 0 Agg = call { i4,...
bool canIgnoreSNaN(fp::ExceptionBehavior EB, FastMathFlags FMF)
Returns true if the possibility of a signaling NaN can be safely ignored.
Definition FPEnv.h:86
LLVM_ABI Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
LLVM_ABI Value * simplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &Q)
Given operands for an ExtractElementInst, fold the result or return null.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This callback is used in conjunction with PointerMayBeCaptured.
virtual Action captured(const Use *U, UseCaptureInfo CI)=0
Use U directly captures CI.UseCC and additionally CI.ResultCC through the return value of the user of...
virtual void tooManyUses()=0
tooManyUses - The depth of traversal has breached a limit.
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition KnownBits.h:310
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
bool CanUseUndef
Controls whether simplifications are allowed to constrain the range of possible values for uses of un...
SimplifyQuery getWithFunction(const Function *F) const
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
LLVM_ABI bool isUndefValue(Value *V) const
If CanUseUndef is true, returns whether V is undef.
AssumptionCache * AC
const Instruction * CtxI
const Function * getFunction() const
const TargetLibraryInfo * TLI
SimplifyQuery getWithoutUndef() const
const InstrInfoQuery IIQ
Capture information for a specific Use.