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