1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/CmpInstAnalysis.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/Transforms/Utils/Local.h"
17 #include "llvm/IR/ConstantRange.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/PatternMatch.h"
21 using namespace PatternMatch
;
23 #define DEBUG_TYPE "instcombine"
25 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
27 static unsigned getFCmpCode(FCmpInst::Predicate CC
) {
28 assert(FCmpInst::FCMP_FALSE
<= CC
&& CC
<= FCmpInst::FCMP_TRUE
&&
29 "Unexpected FCmp predicate!");
30 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 static_assert(FCmpInst::FCMP_FALSE
== 0, ""); // 0 0 0 0
33 static_assert(FCmpInst::FCMP_OEQ
== 1, ""); // 0 0 0 1
34 static_assert(FCmpInst::FCMP_OGT
== 2, ""); // 0 0 1 0
35 static_assert(FCmpInst::FCMP_OGE
== 3, ""); // 0 0 1 1
36 static_assert(FCmpInst::FCMP_OLT
== 4, ""); // 0 1 0 0
37 static_assert(FCmpInst::FCMP_OLE
== 5, ""); // 0 1 0 1
38 static_assert(FCmpInst::FCMP_ONE
== 6, ""); // 0 1 1 0
39 static_assert(FCmpInst::FCMP_ORD
== 7, ""); // 0 1 1 1
40 static_assert(FCmpInst::FCMP_UNO
== 8, ""); // 1 0 0 0
41 static_assert(FCmpInst::FCMP_UEQ
== 9, ""); // 1 0 0 1
42 static_assert(FCmpInst::FCMP_UGT
== 10, ""); // 1 0 1 0
43 static_assert(FCmpInst::FCMP_UGE
== 11, ""); // 1 0 1 1
44 static_assert(FCmpInst::FCMP_ULT
== 12, ""); // 1 1 0 0
45 static_assert(FCmpInst::FCMP_ULE
== 13, ""); // 1 1 0 1
46 static_assert(FCmpInst::FCMP_UNE
== 14, ""); // 1 1 1 0
47 static_assert(FCmpInst::FCMP_TRUE
== 15, ""); // 1 1 1 1
51 /// This is the complement of getICmpCode, which turns an opcode and two
52 /// operands into either a constant true or false, or a brand new ICmp
53 /// instruction. The sign is passed in to determine which kind of predicate to
54 /// use in the new icmp instruction.
55 static Value
*getNewICmpValue(unsigned Code
, bool Sign
, Value
*LHS
, Value
*RHS
,
56 InstCombiner::BuilderTy
&Builder
) {
57 ICmpInst::Predicate NewPred
;
58 if (Constant
*TorF
= getPredForICmpCode(Code
, Sign
, LHS
->getType(), NewPred
))
60 return Builder
.CreateICmp(NewPred
, LHS
, RHS
);
63 /// This is the complement of getFCmpCode, which turns an opcode and two
64 /// operands into either a FCmp instruction, or a true/false constant.
65 static Value
*getFCmpValue(unsigned Code
, Value
*LHS
, Value
*RHS
,
66 InstCombiner::BuilderTy
&Builder
) {
67 const auto Pred
= static_cast<FCmpInst::Predicate
>(Code
);
68 assert(FCmpInst::FCMP_FALSE
<= Pred
&& Pred
<= FCmpInst::FCMP_TRUE
&&
69 "Unexpected FCmp predicate!");
70 if (Pred
== FCmpInst::FCMP_FALSE
)
71 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
72 if (Pred
== FCmpInst::FCMP_TRUE
)
73 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 1);
74 return Builder
.CreateFCmp(Pred
, LHS
, RHS
);
77 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
78 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
79 /// \param I Binary operator to transform.
80 /// \return Pointer to node that must replace the original binary operator, or
81 /// null pointer if no transformation was made.
82 static Value
*SimplifyBSwap(BinaryOperator
&I
,
83 InstCombiner::BuilderTy
&Builder
) {
84 assert(I
.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86 Value
*OldLHS
= I
.getOperand(0);
87 Value
*OldRHS
= I
.getOperand(1);
90 if (!match(OldLHS
, m_BSwap(m_Value(NewLHS
))))
96 if (match(OldRHS
, m_BSwap(m_Value(NewRHS
)))) {
97 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
98 if (!OldLHS
->hasOneUse() && !OldRHS
->hasOneUse())
100 // NewRHS initialized by the matcher.
101 } else if (match(OldRHS
, m_APInt(C
))) {
102 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
103 if (!OldLHS
->hasOneUse())
105 NewRHS
= ConstantInt::get(I
.getType(), C
->byteSwap());
109 Value
*BinOp
= Builder
.CreateBinOp(I
.getOpcode(), NewLHS
, NewRHS
);
110 Function
*F
= Intrinsic::getDeclaration(I
.getModule(), Intrinsic::bswap
,
112 return Builder
.CreateCall(F
, BinOp
);
115 /// This handles expressions of the form ((val OP C1) & C2). Where
116 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
117 Instruction
*InstCombiner::OptAndOp(BinaryOperator
*Op
,
120 BinaryOperator
&TheAnd
) {
121 Value
*X
= Op
->getOperand(0);
123 switch (Op
->getOpcode()) {
125 case Instruction::Add
:
126 if (Op
->hasOneUse()) {
127 // Adding a one to a single bit bit-field should be turned into an XOR
128 // of the bit. First thing to check is to see if this AND is with a
129 // single bit constant.
130 const APInt
&AndRHSV
= AndRHS
->getValue();
132 // If there is only one bit set.
133 if (AndRHSV
.isPowerOf2()) {
134 // Ok, at this point, we know that we are masking the result of the
135 // ADD down to exactly one bit. If the constant we are adding has
136 // no bits set below this bit, then we can eliminate the ADD.
137 const APInt
& AddRHS
= OpRHS
->getValue();
139 // Check to see if any bits below the one bit set in AndRHSV are set.
140 if ((AddRHS
& (AndRHSV
- 1)).isNullValue()) {
141 // If not, the only thing that can effect the output of the AND is
142 // the bit specified by AndRHSV. If that bit is set, the effect of
143 // the XOR is to toggle the bit. If it is clear, then the ADD has
145 if ((AddRHS
& AndRHSV
).isNullValue()) { // Bit is not set, noop
146 TheAnd
.setOperand(0, X
);
149 // Pull the XOR out of the AND.
150 Value
*NewAnd
= Builder
.CreateAnd(X
, AndRHS
);
151 NewAnd
->takeName(Op
);
152 return BinaryOperator::CreateXor(NewAnd
, AndRHS
);
162 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
163 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
164 /// whether to treat V, Lo, and Hi as signed or not.
165 Value
*InstCombiner::insertRangeTest(Value
*V
, const APInt
&Lo
, const APInt
&Hi
,
166 bool isSigned
, bool Inside
) {
167 assert((isSigned
? Lo
.slt(Hi
) : Lo
.ult(Hi
)) &&
168 "Lo is not < Hi in range emission code!");
170 Type
*Ty
= V
->getType();
172 // V >= Min && V < Hi --> V < Hi
173 // V < Min || V >= Hi --> V >= Hi
174 ICmpInst::Predicate Pred
= Inside
? ICmpInst::ICMP_ULT
: ICmpInst::ICMP_UGE
;
175 if (isSigned
? Lo
.isMinSignedValue() : Lo
.isMinValue()) {
176 Pred
= isSigned
? ICmpInst::getSignedPredicate(Pred
) : Pred
;
177 return Builder
.CreateICmp(Pred
, V
, ConstantInt::get(Ty
, Hi
));
180 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
181 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
183 Builder
.CreateSub(V
, ConstantInt::get(Ty
, Lo
), V
->getName() + ".off");
184 Constant
*HiMinusLo
= ConstantInt::get(Ty
, Hi
- Lo
);
185 return Builder
.CreateICmp(Pred
, VMinusLo
, HiMinusLo
);
188 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
189 /// that can be simplified.
190 /// One of A and B is considered the mask. The other is the value. This is
191 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
192 /// only "Mask", then both A and B can be considered masks. If A is the mask,
193 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
194 /// If both A and C are constants, this proof is also easy.
195 /// For the following explanations, we assume that A is the mask.
197 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
198 /// bits of A are set in B.
199 /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
201 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
202 /// bits of A are cleared in B.
203 /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
205 /// "Mixed" declares that (A & B) == C and C might or might not contain any
206 /// number of one bits and zero bits.
207 /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
209 /// "Not" means that in above descriptions "==" should be replaced by "!=".
210 /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
212 /// If the mask A contains a single bit, then the following is equivalent:
213 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
214 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
215 enum MaskedICmpType
{
217 AMask_NotAllOnes
= 2,
219 BMask_NotAllOnes
= 8,
221 Mask_NotAllZeros
= 32,
223 AMask_NotMixed
= 128,
228 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
230 static unsigned getMaskedICmpType(Value
*A
, Value
*B
, Value
*C
,
231 ICmpInst::Predicate Pred
) {
232 ConstantInt
*ACst
= dyn_cast
<ConstantInt
>(A
);
233 ConstantInt
*BCst
= dyn_cast
<ConstantInt
>(B
);
234 ConstantInt
*CCst
= dyn_cast
<ConstantInt
>(C
);
235 bool IsEq
= (Pred
== ICmpInst::ICMP_EQ
);
236 bool IsAPow2
= (ACst
&& !ACst
->isZero() && ACst
->getValue().isPowerOf2());
237 bool IsBPow2
= (BCst
&& !BCst
->isZero() && BCst
->getValue().isPowerOf2());
238 unsigned MaskVal
= 0;
239 if (CCst
&& CCst
->isZero()) {
240 // if C is zero, then both A and B qualify as mask
241 MaskVal
|= (IsEq
? (Mask_AllZeros
| AMask_Mixed
| BMask_Mixed
)
242 : (Mask_NotAllZeros
| AMask_NotMixed
| BMask_NotMixed
));
244 MaskVal
|= (IsEq
? (AMask_NotAllOnes
| AMask_NotMixed
)
245 : (AMask_AllOnes
| AMask_Mixed
));
247 MaskVal
|= (IsEq
? (BMask_NotAllOnes
| BMask_NotMixed
)
248 : (BMask_AllOnes
| BMask_Mixed
));
253 MaskVal
|= (IsEq
? (AMask_AllOnes
| AMask_Mixed
)
254 : (AMask_NotAllOnes
| AMask_NotMixed
));
256 MaskVal
|= (IsEq
? (Mask_NotAllZeros
| AMask_NotMixed
)
257 : (Mask_AllZeros
| AMask_Mixed
));
258 } else if (ACst
&& CCst
&& ConstantExpr::getAnd(ACst
, CCst
) == CCst
) {
259 MaskVal
|= (IsEq
? AMask_Mixed
: AMask_NotMixed
);
263 MaskVal
|= (IsEq
? (BMask_AllOnes
| BMask_Mixed
)
264 : (BMask_NotAllOnes
| BMask_NotMixed
));
266 MaskVal
|= (IsEq
? (Mask_NotAllZeros
| BMask_NotMixed
)
267 : (Mask_AllZeros
| BMask_Mixed
));
268 } else if (BCst
&& CCst
&& ConstantExpr::getAnd(BCst
, CCst
) == CCst
) {
269 MaskVal
|= (IsEq
? BMask_Mixed
: BMask_NotMixed
);
275 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
276 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
277 /// is adjacent to the corresponding normal flag (recording ==), this just
278 /// involves swapping those bits over.
279 static unsigned conjugateICmpMask(unsigned Mask
) {
281 NewMask
= (Mask
& (AMask_AllOnes
| BMask_AllOnes
| Mask_AllZeros
|
282 AMask_Mixed
| BMask_Mixed
))
285 NewMask
|= (Mask
& (AMask_NotAllOnes
| BMask_NotAllOnes
| Mask_NotAllZeros
|
286 AMask_NotMixed
| BMask_NotMixed
))
292 // Adapts the external decomposeBitTestICmp for local use.
293 static bool decomposeBitTestICmp(Value
*LHS
, Value
*RHS
, CmpInst::Predicate
&Pred
,
294 Value
*&X
, Value
*&Y
, Value
*&Z
) {
296 if (!llvm::decomposeBitTestICmp(LHS
, RHS
, Pred
, X
, Mask
))
299 Y
= ConstantInt::get(X
->getType(), Mask
);
300 Z
= ConstantInt::get(X
->getType(), 0);
304 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
305 /// Return the pattern classes (from MaskedICmpType) for the left hand side and
306 /// the right hand side as a pair.
307 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
308 /// and PredR are their predicates, respectively.
310 Optional
<std::pair
<unsigned, unsigned>>
311 getMaskedTypeForICmpPair(Value
*&A
, Value
*&B
, Value
*&C
,
312 Value
*&D
, Value
*&E
, ICmpInst
*LHS
,
314 ICmpInst::Predicate
&PredL
,
315 ICmpInst::Predicate
&PredR
) {
316 // vectors are not (yet?) supported. Don't support pointers either.
317 if (!LHS
->getOperand(0)->getType()->isIntegerTy() ||
318 !RHS
->getOperand(0)->getType()->isIntegerTy())
321 // Here comes the tricky part:
322 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
323 // and L11 & L12 == L21 & L22. The same goes for RHS.
324 // Now we must find those components L** and R**, that are equal, so
325 // that we can extract the parameters A, B, C, D, and E for the canonical
327 Value
*L1
= LHS
->getOperand(0);
328 Value
*L2
= LHS
->getOperand(1);
329 Value
*L11
, *L12
, *L21
, *L22
;
330 // Check whether the icmp can be decomposed into a bit test.
331 if (decomposeBitTestICmp(L1
, L2
, PredL
, L11
, L12
, L2
)) {
332 L21
= L22
= L1
= nullptr;
334 // Look for ANDs in the LHS icmp.
335 if (!match(L1
, m_And(m_Value(L11
), m_Value(L12
)))) {
336 // Any icmp can be viewed as being trivially masked; if it allows us to
337 // remove one, it's worth it.
339 L12
= Constant::getAllOnesValue(L1
->getType());
342 if (!match(L2
, m_And(m_Value(L21
), m_Value(L22
)))) {
344 L22
= Constant::getAllOnesValue(L2
->getType());
348 // Bail if LHS was a icmp that can't be decomposed into an equality.
349 if (!ICmpInst::isEquality(PredL
))
352 Value
*R1
= RHS
->getOperand(0);
353 Value
*R2
= RHS
->getOperand(1);
356 if (decomposeBitTestICmp(R1
, R2
, PredR
, R11
, R12
, R2
)) {
357 if (R11
== L11
|| R11
== L12
|| R11
== L21
|| R11
== L22
) {
360 } else if (R12
== L11
|| R12
== L12
|| R12
== L21
|| R12
== L22
) {
370 if (!match(R1
, m_And(m_Value(R11
), m_Value(R12
)))) {
371 // As before, model no mask as a trivial mask if it'll let us do an
374 R12
= Constant::getAllOnesValue(R1
->getType());
377 if (R11
== L11
|| R11
== L12
|| R11
== L21
|| R11
== L22
) {
382 } else if (R12
== L11
|| R12
== L12
|| R12
== L21
|| R12
== L22
) {
390 // Bail if RHS was a icmp that can't be decomposed into an equality.
391 if (!ICmpInst::isEquality(PredR
))
394 // Look for ANDs on the right side of the RHS icmp.
396 if (!match(R2
, m_And(m_Value(R11
), m_Value(R12
)))) {
398 R12
= Constant::getAllOnesValue(R2
->getType());
401 if (R11
== L11
|| R11
== L12
|| R11
== L21
|| R11
== L22
) {
406 } else if (R12
== L11
|| R12
== L12
|| R12
== L21
|| R12
== L22
) {
421 } else if (L12
== A
) {
424 } else if (L21
== A
) {
427 } else if (L22
== A
) {
432 unsigned LeftType
= getMaskedICmpType(A
, B
, C
, PredL
);
433 unsigned RightType
= getMaskedICmpType(A
, D
, E
, PredR
);
434 return Optional
<std::pair
<unsigned, unsigned>>(std::make_pair(LeftType
, RightType
));
437 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
438 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
439 /// and the right hand side is of type BMask_Mixed. For example,
440 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
441 static Value
* foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
442 ICmpInst
*LHS
, ICmpInst
*RHS
, bool IsAnd
,
443 Value
*A
, Value
*B
, Value
*C
, Value
*D
, Value
*E
,
444 ICmpInst::Predicate PredL
, ICmpInst::Predicate PredR
,
445 llvm::InstCombiner::BuilderTy
&Builder
) {
446 // We are given the canonical form:
447 // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
450 // If IsAnd is false, we get it in negated form:
451 // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
452 // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
454 // We currently handle the case of B, C, D, E are constant.
456 ConstantInt
*BCst
= dyn_cast
<ConstantInt
>(B
);
459 ConstantInt
*CCst
= dyn_cast
<ConstantInt
>(C
);
462 ConstantInt
*DCst
= dyn_cast
<ConstantInt
>(D
);
465 ConstantInt
*ECst
= dyn_cast
<ConstantInt
>(E
);
469 ICmpInst::Predicate NewCC
= IsAnd
? ICmpInst::ICMP_EQ
: ICmpInst::ICMP_NE
;
471 // Update E to the canonical form when D is a power of two and RHS is
473 // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
474 // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
476 ECst
= cast
<ConstantInt
>(ConstantExpr::getXor(DCst
, ECst
));
478 // If B or D is zero, skip because if LHS or RHS can be trivially folded by
479 // other folding rules and this pattern won't apply any more.
480 if (BCst
->getValue() == 0 || DCst
->getValue() == 0)
483 // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
484 // deduce anything from it.
486 // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
487 if ((BCst
->getValue() & DCst
->getValue()) == 0)
490 // If the following two conditions are met:
492 // 1. mask B covers only a single bit that's not covered by mask D, that is,
493 // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
494 // B and D has only one bit set) and,
496 // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
497 // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
499 // then that single bit in B must be one and thus the whole expression can be
501 // (A & (B | D)) == (B & (B ^ D)) | E.
504 // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
505 // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
506 if ((((BCst
->getValue() & DCst
->getValue()) & ECst
->getValue()) == 0) &&
507 (BCst
->getValue() & (BCst
->getValue() ^ DCst
->getValue())).isPowerOf2()) {
508 APInt BorD
= BCst
->getValue() | DCst
->getValue();
509 APInt BandBxorDorE
= (BCst
->getValue() & (BCst
->getValue() ^ DCst
->getValue())) |
511 Value
*NewMask
= ConstantInt::get(BCst
->getType(), BorD
);
512 Value
*NewMaskedValue
= ConstantInt::get(BCst
->getType(), BandBxorDorE
);
513 Value
*NewAnd
= Builder
.CreateAnd(A
, NewMask
);
514 return Builder
.CreateICmp(NewCC
, NewAnd
, NewMaskedValue
);
517 auto IsSubSetOrEqual
= [](ConstantInt
*C1
, ConstantInt
*C2
) {
518 return (C1
->getValue() & C2
->getValue()) == C1
->getValue();
520 auto IsSuperSetOrEqual
= [](ConstantInt
*C1
, ConstantInt
*C2
) {
521 return (C1
->getValue() & C2
->getValue()) == C2
->getValue();
524 // In the following, we consider only the cases where B is a superset of D, B
525 // is a subset of D, or B == D because otherwise there's at least one bit
526 // covered by B but not D, in which case we can't deduce much from it, so
527 // no folding (aside from the single must-be-one bit case right above.)
529 // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
530 if (!IsSubSetOrEqual(BCst
, DCst
) && !IsSuperSetOrEqual(BCst
, DCst
))
533 // At this point, either B is a superset of D, B is a subset of D or B == D.
535 // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
536 // and the whole expression becomes false (or true if negated), otherwise, no
539 // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
540 // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
541 if (ECst
->isZero()) {
542 if (IsSubSetOrEqual(BCst
, DCst
))
543 return ConstantInt::get(LHS
->getType(), !IsAnd
);
547 // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
548 // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
549 // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
551 // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
552 // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
553 if (IsSuperSetOrEqual(BCst
, DCst
))
555 // Otherwise, B is a subset of D. If B and E have a common bit set,
556 // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
557 // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
558 assert(IsSubSetOrEqual(BCst
, DCst
) && "Precondition due to above code");
559 if ((BCst
->getValue() & ECst
->getValue()) != 0)
561 // Otherwise, LHS and RHS contradict and the whole expression becomes false
562 // (or true if negated.) For example,
563 // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
564 // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
565 return ConstantInt::get(LHS
->getType(), !IsAnd
);
568 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
569 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
570 /// aren't of the common mask pattern type.
571 static Value
*foldLogOpOfMaskedICmpsAsymmetric(
572 ICmpInst
*LHS
, ICmpInst
*RHS
, bool IsAnd
,
573 Value
*A
, Value
*B
, Value
*C
, Value
*D
, Value
*E
,
574 ICmpInst::Predicate PredL
, ICmpInst::Predicate PredR
,
575 unsigned LHSMask
, unsigned RHSMask
,
576 llvm::InstCombiner::BuilderTy
&Builder
) {
577 assert(ICmpInst::isEquality(PredL
) && ICmpInst::isEquality(PredR
) &&
578 "Expected equality predicates for masked type of icmps.");
579 // Handle Mask_NotAllZeros-BMask_Mixed cases.
580 // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
581 // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
582 // which gets swapped to
583 // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
585 LHSMask
= conjugateICmpMask(LHSMask
);
586 RHSMask
= conjugateICmpMask(RHSMask
);
588 if ((LHSMask
& Mask_NotAllZeros
) && (RHSMask
& BMask_Mixed
)) {
589 if (Value
*V
= foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
590 LHS
, RHS
, IsAnd
, A
, B
, C
, D
, E
,
591 PredL
, PredR
, Builder
)) {
594 } else if ((LHSMask
& BMask_Mixed
) && (RHSMask
& Mask_NotAllZeros
)) {
595 if (Value
*V
= foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
596 RHS
, LHS
, IsAnd
, A
, D
, E
, B
, C
,
597 PredR
, PredL
, Builder
)) {
604 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
605 /// into a single (icmp(A & X) ==/!= Y).
606 static Value
*foldLogOpOfMaskedICmps(ICmpInst
*LHS
, ICmpInst
*RHS
, bool IsAnd
,
607 llvm::InstCombiner::BuilderTy
&Builder
) {
608 Value
*A
= nullptr, *B
= nullptr, *C
= nullptr, *D
= nullptr, *E
= nullptr;
609 ICmpInst::Predicate PredL
= LHS
->getPredicate(), PredR
= RHS
->getPredicate();
610 Optional
<std::pair
<unsigned, unsigned>> MaskPair
=
611 getMaskedTypeForICmpPair(A
, B
, C
, D
, E
, LHS
, RHS
, PredL
, PredR
);
614 assert(ICmpInst::isEquality(PredL
) && ICmpInst::isEquality(PredR
) &&
615 "Expected equality predicates for masked type of icmps.");
616 unsigned LHSMask
= MaskPair
->first
;
617 unsigned RHSMask
= MaskPair
->second
;
618 unsigned Mask
= LHSMask
& RHSMask
;
620 // Even if the two sides don't share a common pattern, check if folding can
622 if (Value
*V
= foldLogOpOfMaskedICmpsAsymmetric(
623 LHS
, RHS
, IsAnd
, A
, B
, C
, D
, E
, PredL
, PredR
, LHSMask
, RHSMask
,
629 // In full generality:
630 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
631 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
633 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
634 // equivalent to (icmp (A & X) !Op Y).
636 // Therefore, we can pretend for the rest of this function that we're dealing
637 // with the conjunction, provided we flip the sense of any comparisons (both
638 // input and output).
640 // In most cases we're going to produce an EQ for the "&&" case.
641 ICmpInst::Predicate NewCC
= IsAnd
? ICmpInst::ICMP_EQ
: ICmpInst::ICMP_NE
;
643 // Convert the masking analysis into its equivalent with negated
645 Mask
= conjugateICmpMask(Mask
);
648 if (Mask
& Mask_AllZeros
) {
649 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
650 // -> (icmp eq (A & (B|D)), 0)
651 Value
*NewOr
= Builder
.CreateOr(B
, D
);
652 Value
*NewAnd
= Builder
.CreateAnd(A
, NewOr
);
653 // We can't use C as zero because we might actually handle
654 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
655 // with B and D, having a single bit set.
656 Value
*Zero
= Constant::getNullValue(A
->getType());
657 return Builder
.CreateICmp(NewCC
, NewAnd
, Zero
);
659 if (Mask
& BMask_AllOnes
) {
660 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
661 // -> (icmp eq (A & (B|D)), (B|D))
662 Value
*NewOr
= Builder
.CreateOr(B
, D
);
663 Value
*NewAnd
= Builder
.CreateAnd(A
, NewOr
);
664 return Builder
.CreateICmp(NewCC
, NewAnd
, NewOr
);
666 if (Mask
& AMask_AllOnes
) {
667 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
668 // -> (icmp eq (A & (B&D)), A)
669 Value
*NewAnd1
= Builder
.CreateAnd(B
, D
);
670 Value
*NewAnd2
= Builder
.CreateAnd(A
, NewAnd1
);
671 return Builder
.CreateICmp(NewCC
, NewAnd2
, A
);
674 // Remaining cases assume at least that B and D are constant, and depend on
675 // their actual values. This isn't strictly necessary, just a "handle the
676 // easy cases for now" decision.
677 ConstantInt
*BCst
= dyn_cast
<ConstantInt
>(B
);
680 ConstantInt
*DCst
= dyn_cast
<ConstantInt
>(D
);
684 if (Mask
& (Mask_NotAllZeros
| BMask_NotAllOnes
)) {
685 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
686 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
687 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
688 // Only valid if one of the masks is a superset of the other (check "B&D" is
689 // the same as either B or D).
690 APInt NewMask
= BCst
->getValue() & DCst
->getValue();
692 if (NewMask
== BCst
->getValue())
694 else if (NewMask
== DCst
->getValue())
698 if (Mask
& AMask_NotAllOnes
) {
699 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
700 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
701 // Only valid if one of the masks is a superset of the other (check "B|D" is
702 // the same as either B or D).
703 APInt NewMask
= BCst
->getValue() | DCst
->getValue();
705 if (NewMask
== BCst
->getValue())
707 else if (NewMask
== DCst
->getValue())
711 if (Mask
& BMask_Mixed
) {
712 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
713 // We already know that B & C == C && D & E == E.
714 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
715 // C and E, which are shared by both the mask B and the mask D, don't
716 // contradict, then we can transform to
717 // -> (icmp eq (A & (B|D)), (C|E))
718 // Currently, we only handle the case of B, C, D, and E being constant.
719 // We can't simply use C and E because we might actually handle
720 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
721 // with B and D, having a single bit set.
722 ConstantInt
*CCst
= dyn_cast
<ConstantInt
>(C
);
725 ConstantInt
*ECst
= dyn_cast
<ConstantInt
>(E
);
729 CCst
= cast
<ConstantInt
>(ConstantExpr::getXor(BCst
, CCst
));
731 ECst
= cast
<ConstantInt
>(ConstantExpr::getXor(DCst
, ECst
));
733 // If there is a conflict, we should actually return a false for the
735 if (((BCst
->getValue() & DCst
->getValue()) &
736 (CCst
->getValue() ^ ECst
->getValue())).getBoolValue())
737 return ConstantInt::get(LHS
->getType(), !IsAnd
);
739 Value
*NewOr1
= Builder
.CreateOr(B
, D
);
740 Value
*NewOr2
= ConstantExpr::getOr(CCst
, ECst
);
741 Value
*NewAnd
= Builder
.CreateAnd(A
, NewOr1
);
742 return Builder
.CreateICmp(NewCC
, NewAnd
, NewOr2
);
748 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
749 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
750 /// If \p Inverted is true then the check is for the inverted range, e.g.
751 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
752 Value
*InstCombiner::simplifyRangeCheck(ICmpInst
*Cmp0
, ICmpInst
*Cmp1
,
754 // Check the lower range comparison, e.g. x >= 0
755 // InstCombine already ensured that if there is a constant it's on the RHS.
756 ConstantInt
*RangeStart
= dyn_cast
<ConstantInt
>(Cmp0
->getOperand(1));
760 ICmpInst::Predicate Pred0
= (Inverted
? Cmp0
->getInversePredicate() :
761 Cmp0
->getPredicate());
763 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
764 if (!((Pred0
== ICmpInst::ICMP_SGT
&& RangeStart
->isMinusOne()) ||
765 (Pred0
== ICmpInst::ICMP_SGE
&& RangeStart
->isZero())))
768 ICmpInst::Predicate Pred1
= (Inverted
? Cmp1
->getInversePredicate() :
769 Cmp1
->getPredicate());
771 Value
*Input
= Cmp0
->getOperand(0);
773 if (Cmp1
->getOperand(0) == Input
) {
774 // For the upper range compare we have: icmp x, n
775 RangeEnd
= Cmp1
->getOperand(1);
776 } else if (Cmp1
->getOperand(1) == Input
) {
777 // For the upper range compare we have: icmp n, x
778 RangeEnd
= Cmp1
->getOperand(0);
779 Pred1
= ICmpInst::getSwappedPredicate(Pred1
);
784 // Check the upper range comparison, e.g. x < n
785 ICmpInst::Predicate NewPred
;
787 case ICmpInst::ICMP_SLT
: NewPred
= ICmpInst::ICMP_ULT
; break;
788 case ICmpInst::ICMP_SLE
: NewPred
= ICmpInst::ICMP_ULE
; break;
789 default: return nullptr;
792 // This simplification is only valid if the upper range is not negative.
793 KnownBits Known
= computeKnownBits(RangeEnd
, /*Depth=*/0, Cmp1
);
794 if (!Known
.isNonNegative())
798 NewPred
= ICmpInst::getInversePredicate(NewPred
);
800 return Builder
.CreateICmp(NewPred
, Input
, RangeEnd
);
804 foldAndOrOfEqualityCmpsWithConstants(ICmpInst
*LHS
, ICmpInst
*RHS
,
806 InstCombiner::BuilderTy
&Builder
) {
807 Value
*X
= LHS
->getOperand(0);
808 if (X
!= RHS
->getOperand(0))
811 const APInt
*C1
, *C2
;
812 if (!match(LHS
->getOperand(1), m_APInt(C1
)) ||
813 !match(RHS
->getOperand(1), m_APInt(C2
)))
816 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
817 ICmpInst::Predicate Pred
= LHS
->getPredicate();
818 if (Pred
!= RHS
->getPredicate())
820 if (JoinedByAnd
&& Pred
!= ICmpInst::ICMP_NE
)
822 if (!JoinedByAnd
&& Pred
!= ICmpInst::ICMP_EQ
)
825 // The larger unsigned constant goes on the right.
829 APInt Xor
= *C1
^ *C2
;
830 if (Xor
.isPowerOf2()) {
831 // If LHSC and RHSC differ by only one bit, then set that bit in X and
832 // compare against the larger constant:
833 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
834 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
835 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
836 // 'and' because that may lead to smaller codegen from a smaller constant.
837 Value
*Or
= Builder
.CreateOr(X
, ConstantInt::get(X
->getType(), Xor
));
838 return Builder
.CreateICmp(Pred
, Or
, ConstantInt::get(X
->getType(), *C2
));
841 // Special case: get the ordering right when the values wrap around zero.
842 // Ie, we assumed the constants were unsigned when swapping earlier.
843 if (C1
->isNullValue() && C2
->isAllOnesValue())
846 if (*C1
== *C2
- 1) {
847 // (X == 13 || X == 14) --> X - 13 <=u 1
848 // (X != 13 && X != 14) --> X - 13 >u 1
849 // An 'add' is the canonical IR form, so favor that over a 'sub'.
850 Value
*Add
= Builder
.CreateAdd(X
, ConstantInt::get(X
->getType(), -(*C1
)));
851 auto NewPred
= JoinedByAnd
? ICmpInst::ICMP_UGT
: ICmpInst::ICMP_ULE
;
852 return Builder
.CreateICmp(NewPred
, Add
, ConstantInt::get(X
->getType(), 1));
858 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
859 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
860 Value
*InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst
*LHS
, ICmpInst
*RHS
,
863 ICmpInst::Predicate Pred
= LHS
->getPredicate();
864 if (Pred
!= RHS
->getPredicate())
866 if (JoinedByAnd
&& Pred
!= ICmpInst::ICMP_NE
)
868 if (!JoinedByAnd
&& Pred
!= ICmpInst::ICMP_EQ
)
871 // TODO support vector splats
872 ConstantInt
*LHSC
= dyn_cast
<ConstantInt
>(LHS
->getOperand(1));
873 ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(RHS
->getOperand(1));
874 if (!LHSC
|| !RHSC
|| !LHSC
->isZero() || !RHSC
->isZero())
877 Value
*A
, *B
, *C
, *D
;
878 if (match(LHS
->getOperand(0), m_And(m_Value(A
), m_Value(B
))) &&
879 match(RHS
->getOperand(0), m_And(m_Value(C
), m_Value(D
)))) {
880 if (A
== D
|| B
== D
)
886 isKnownToBeAPowerOfTwo(B
, false, 0, &CxtI
) &&
887 isKnownToBeAPowerOfTwo(D
, false, 0, &CxtI
)) {
888 Value
*Mask
= Builder
.CreateOr(B
, D
);
889 Value
*Masked
= Builder
.CreateAnd(A
, Mask
);
890 auto NewPred
= JoinedByAnd
? ICmpInst::ICMP_EQ
: ICmpInst::ICMP_NE
;
891 return Builder
.CreateICmp(NewPred
, Masked
, Mask
);
901 /// Where Y is checking that all the high bits (covered by a mask 4294967168)
902 /// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
903 /// Pattern can be one of:
904 /// %t = add i32 %arg, 128
905 /// %r = icmp ult i32 %t, 256
907 /// %t0 = shl i32 %arg, 24
908 /// %t1 = ashr i32 %t0, 24
909 /// %r = icmp eq i32 %t1, %arg
911 /// %t0 = trunc i32 %arg to i8
912 /// %t1 = sext i8 %t0 to i32
913 /// %r = icmp eq i32 %t1, %arg
914 /// This pattern is a signed truncation check.
916 /// And X is checking that some bit in that same mask is zero.
917 /// I.e. can be one of:
918 /// %r = icmp sgt i32 %arg, -1
920 /// %t = and i32 %arg, 2147483648
921 /// %r = icmp eq i32 %t, 0
923 /// Since we are checking that all the bits in that mask are the same,
924 /// and a particular bit is zero, what we are really checking is that all the
925 /// masked bits are zero.
926 /// So this should be transformed to:
927 /// %r = icmp ult i32 %arg, 128
928 static Value
*foldSignedTruncationCheck(ICmpInst
*ICmp0
, ICmpInst
*ICmp1
,
930 InstCombiner::BuilderTy
&Builder
) {
931 assert(CxtI
.getOpcode() == Instruction::And
);
933 // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
934 auto tryToMatchSignedTruncationCheck
= [](ICmpInst
*ICmp
, Value
*&X
,
935 APInt
&SignBitMask
) -> bool {
936 CmpInst::Predicate Pred
;
937 const APInt
*I01
, *I1
; // powers of two; I1 == I01 << 1
939 m_ICmp(Pred
, m_Add(m_Value(X
), m_Power2(I01
)), m_Power2(I1
))) &&
940 Pred
== ICmpInst::ICMP_ULT
&& I1
->ugt(*I01
) && I01
->shl(1) == *I1
))
942 // Which bit is the new sign bit as per the 'signed truncation' pattern?
947 // One icmp needs to be 'signed truncation check'.
948 // We need to match this first, else we will mismatch commutative cases.
952 if (tryToMatchSignedTruncationCheck(ICmp1
, X1
, HighestBit
))
954 else if (tryToMatchSignedTruncationCheck(ICmp0
, X1
, HighestBit
))
959 assert(HighestBit
.isPowerOf2() && "expected to be power of two (non-zero)");
961 // Try to match/decompose into: icmp eq (X & Mask), 0
962 auto tryToDecompose
= [](ICmpInst
*ICmp
, Value
*&X
,
963 APInt
&UnsetBitsMask
) -> bool {
964 CmpInst::Predicate Pred
= ICmp
->getPredicate();
965 // Can it be decomposed into icmp eq (X & Mask), 0 ?
966 if (llvm::decomposeBitTestICmp(ICmp
->getOperand(0), ICmp
->getOperand(1),
967 Pred
, X
, UnsetBitsMask
,
968 /*LookThroughTrunc=*/false) &&
969 Pred
== ICmpInst::ICMP_EQ
)
971 // Is it icmp eq (X & Mask), 0 already?
973 if (match(ICmp
, m_ICmp(Pred
, m_And(m_Value(X
), m_APInt(Mask
)), m_Zero())) &&
974 Pred
== ICmpInst::ICMP_EQ
) {
975 UnsetBitsMask
= *Mask
;
981 // And the other icmp needs to be decomposable into a bit test.
984 if (!tryToDecompose(OtherICmp
, X0
, UnsetBitsMask
))
987 assert(!UnsetBitsMask
.isNullValue() && "empty mask makes no sense.");
989 // Are they working on the same value?
994 } else if (match(X0
, m_Trunc(m_Specific(X1
)))) {
995 UnsetBitsMask
= UnsetBitsMask
.zext(X1
->getType()->getScalarSizeInBits());
1000 // So which bits should be uniform as per the 'signed truncation check'?
1001 // (all the bits starting with (i.e. including) HighestBit)
1002 APInt SignBitsMask
= ~(HighestBit
- 1U);
1004 // UnsetBitsMask must have some common bits with SignBitsMask,
1005 if (!UnsetBitsMask
.intersects(SignBitsMask
))
1008 // Does UnsetBitsMask contain any bits outside of SignBitsMask?
1009 if (!UnsetBitsMask
.isSubsetOf(SignBitsMask
)) {
1010 APInt OtherHighestBit
= (~UnsetBitsMask
) + 1U;
1011 if (!OtherHighestBit
.isPowerOf2())
1013 HighestBit
= APIntOps::umin(HighestBit
, OtherHighestBit
);
1015 // Else, if it does not, then all is ok as-is.
1017 // %r = icmp ult %X, SignBit
1018 return Builder
.CreateICmpULT(X
, ConstantInt::get(X
->getType(), HighestBit
),
1019 CxtI
.getName() + ".simplified");
1022 /// Reduce a pair of compares that check if a value has exactly 1 bit set.
1023 static Value
*foldIsPowerOf2(ICmpInst
*Cmp0
, ICmpInst
*Cmp1
, bool JoinedByAnd
,
1024 InstCombiner::BuilderTy
&Builder
) {
1025 // Handle 'and' / 'or' commutation: make the equality check the first operand.
1026 if (JoinedByAnd
&& Cmp1
->getPredicate() == ICmpInst::ICMP_NE
)
1027 std::swap(Cmp0
, Cmp1
);
1028 else if (!JoinedByAnd
&& Cmp1
->getPredicate() == ICmpInst::ICMP_EQ
)
1029 std::swap(Cmp0
, Cmp1
);
1031 // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
1032 CmpInst::Predicate Pred0
, Pred1
;
1034 if (JoinedByAnd
&& match(Cmp0
, m_ICmp(Pred0
, m_Value(X
), m_ZeroInt())) &&
1035 match(Cmp1
, m_ICmp(Pred1
, m_Intrinsic
<Intrinsic::ctpop
>(m_Specific(X
)),
1036 m_SpecificInt(2))) &&
1037 Pred0
== ICmpInst::ICMP_NE
&& Pred1
== ICmpInst::ICMP_ULT
) {
1038 Value
*CtPop
= Cmp1
->getOperand(0);
1039 return Builder
.CreateICmpEQ(CtPop
, ConstantInt::get(CtPop
->getType(), 1));
1041 // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
1042 if (!JoinedByAnd
&& match(Cmp0
, m_ICmp(Pred0
, m_Value(X
), m_ZeroInt())) &&
1043 match(Cmp1
, m_ICmp(Pred1
, m_Intrinsic
<Intrinsic::ctpop
>(m_Specific(X
)),
1044 m_SpecificInt(1))) &&
1045 Pred0
== ICmpInst::ICMP_EQ
&& Pred1
== ICmpInst::ICMP_UGT
) {
1046 Value
*CtPop
= Cmp1
->getOperand(0);
1047 return Builder
.CreateICmpNE(CtPop
, ConstantInt::get(CtPop
->getType(), 1));
1052 /// Commuted variants are assumed to be handled by calling this function again
1053 /// with the parameters swapped.
1054 static Value
*foldUnsignedUnderflowCheck(ICmpInst
*ZeroICmp
,
1055 ICmpInst
*UnsignedICmp
, bool IsAnd
,
1056 const SimplifyQuery
&Q
,
1057 InstCombiner::BuilderTy
&Builder
) {
1059 ICmpInst::Predicate EqPred
;
1060 if (!match(ZeroICmp
, m_ICmp(EqPred
, m_Value(ZeroCmpOp
), m_Zero())) ||
1061 !ICmpInst::isEquality(EqPred
))
1064 Value
*Base
, *Offset
;
1065 if (!match(ZeroCmpOp
, m_Sub(m_Value(Base
), m_Value(Offset
))))
1068 ICmpInst::Predicate UnsignedPred
;
1070 // ZeroCmpOp < Base && ZeroCmpOp != 0 --> Base > Offset iff Offset != 0
1071 // ZeroCmpOp >= Base || ZeroCmpOp == 0 --> Base <= Base iff Offset != 0
1072 if (match(UnsignedICmp
,
1073 m_c_ICmp(UnsignedPred
, m_Specific(ZeroCmpOp
), m_Specific(Base
)))) {
1074 if (UnsignedICmp
->getOperand(0) != ZeroCmpOp
)
1075 UnsignedPred
= ICmpInst::getSwappedPredicate(UnsignedPred
);
1077 if (UnsignedPred
== ICmpInst::ICMP_ULT
&& IsAnd
&&
1078 EqPred
== ICmpInst::ICMP_NE
&&
1079 isKnownNonZero(Offset
, Q
.DL
, /*Depth=*/0, Q
.AC
, Q
.CxtI
, Q
.DT
))
1080 return Builder
.CreateICmpUGT(Base
, Offset
);
1081 if (UnsignedPred
== ICmpInst::ICMP_UGE
&& !IsAnd
&&
1082 EqPred
== ICmpInst::ICMP_EQ
&&
1083 isKnownNonZero(Offset
, Q
.DL
, /*Depth=*/0, Q
.AC
, Q
.CxtI
, Q
.DT
))
1084 return Builder
.CreateICmpULE(Base
, Offset
);
1087 if (!match(UnsignedICmp
,
1088 m_c_ICmp(UnsignedPred
, m_Specific(Base
), m_Specific(Offset
))) ||
1089 !ICmpInst::isUnsigned(UnsignedPred
))
1091 if (UnsignedICmp
->getOperand(0) != Base
)
1092 UnsignedPred
= ICmpInst::getSwappedPredicate(UnsignedPred
);
1094 // Base >=/> Offset && (Base - Offset) != 0 <--> Base > Offset
1095 // (no overflow and not null)
1096 if ((UnsignedPred
== ICmpInst::ICMP_UGE
||
1097 UnsignedPred
== ICmpInst::ICMP_UGT
) &&
1098 EqPred
== ICmpInst::ICMP_NE
&& IsAnd
)
1099 return Builder
.CreateICmpUGT(Base
, Offset
);
1101 // Base <=/< Offset || (Base - Offset) == 0 <--> Base <= Offset
1102 // (overflow or null)
1103 if ((UnsignedPred
== ICmpInst::ICMP_ULE
||
1104 UnsignedPred
== ICmpInst::ICMP_ULT
) &&
1105 EqPred
== ICmpInst::ICMP_EQ
&& !IsAnd
)
1106 return Builder
.CreateICmpULE(Base
, Offset
);
1111 /// Fold (icmp)&(icmp) if possible.
1112 Value
*InstCombiner::foldAndOfICmps(ICmpInst
*LHS
, ICmpInst
*RHS
,
1113 Instruction
&CxtI
) {
1114 const SimplifyQuery Q
= SQ
.getWithInstruction(&CxtI
);
1116 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
1117 // if K1 and K2 are a one-bit mask.
1118 if (Value
*V
= foldAndOrOfICmpsOfAndWithPow2(LHS
, RHS
, true, CxtI
))
1121 ICmpInst::Predicate PredL
= LHS
->getPredicate(), PredR
= RHS
->getPredicate();
1123 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1124 if (predicatesFoldable(PredL
, PredR
)) {
1125 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
1126 LHS
->getOperand(1) == RHS
->getOperand(0))
1127 LHS
->swapOperands();
1128 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
1129 LHS
->getOperand(1) == RHS
->getOperand(1)) {
1130 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
1131 unsigned Code
= getICmpCode(LHS
) & getICmpCode(RHS
);
1132 bool IsSigned
= LHS
->isSigned() || RHS
->isSigned();
1133 return getNewICmpValue(Code
, IsSigned
, Op0
, Op1
, Builder
);
1137 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
1138 if (Value
*V
= foldLogOpOfMaskedICmps(LHS
, RHS
, true, Builder
))
1141 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
1142 if (Value
*V
= simplifyRangeCheck(LHS
, RHS
, /*Inverted=*/false))
1145 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
1146 if (Value
*V
= simplifyRangeCheck(RHS
, LHS
, /*Inverted=*/false))
1149 if (Value
*V
= foldAndOrOfEqualityCmpsWithConstants(LHS
, RHS
, true, Builder
))
1152 if (Value
*V
= foldSignedTruncationCheck(LHS
, RHS
, CxtI
, Builder
))
1155 if (Value
*V
= foldIsPowerOf2(LHS
, RHS
, true /* JoinedByAnd */, Builder
))
1159 foldUnsignedUnderflowCheck(LHS
, RHS
, /*IsAnd=*/true, Q
, Builder
))
1162 foldUnsignedUnderflowCheck(RHS
, LHS
, /*IsAnd=*/true, Q
, Builder
))
1165 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
1166 Value
*LHS0
= LHS
->getOperand(0), *RHS0
= RHS
->getOperand(0);
1167 ConstantInt
*LHSC
= dyn_cast
<ConstantInt
>(LHS
->getOperand(1));
1168 ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(RHS
->getOperand(1));
1172 if (LHSC
== RHSC
&& PredL
== PredR
) {
1173 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1174 // where C is a power of 2 or
1175 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1176 if ((PredL
== ICmpInst::ICMP_ULT
&& LHSC
->getValue().isPowerOf2()) ||
1177 (PredL
== ICmpInst::ICMP_EQ
&& LHSC
->isZero())) {
1178 Value
*NewOr
= Builder
.CreateOr(LHS0
, RHS0
);
1179 return Builder
.CreateICmp(PredL
, NewOr
, LHSC
);
1183 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
1184 // where CMAX is the all ones value for the truncated type,
1185 // iff the lower bits of C2 and CA are zero.
1186 if (PredL
== ICmpInst::ICMP_EQ
&& PredL
== PredR
&& LHS
->hasOneUse() &&
1189 ConstantInt
*AndC
, *SmallC
= nullptr, *BigC
= nullptr;
1191 // (trunc x) == C1 & (and x, CA) == C2
1192 // (and x, CA) == C2 & (trunc x) == C1
1193 if (match(RHS0
, m_Trunc(m_Value(V
))) &&
1194 match(LHS0
, m_And(m_Specific(V
), m_ConstantInt(AndC
)))) {
1197 } else if (match(LHS0
, m_Trunc(m_Value(V
))) &&
1198 match(RHS0
, m_And(m_Specific(V
), m_ConstantInt(AndC
)))) {
1203 if (SmallC
&& BigC
) {
1204 unsigned BigBitSize
= BigC
->getType()->getBitWidth();
1205 unsigned SmallBitSize
= SmallC
->getType()->getBitWidth();
1207 // Check that the low bits are zero.
1208 APInt Low
= APInt::getLowBitsSet(BigBitSize
, SmallBitSize
);
1209 if ((Low
& AndC
->getValue()).isNullValue() &&
1210 (Low
& BigC
->getValue()).isNullValue()) {
1211 Value
*NewAnd
= Builder
.CreateAnd(V
, Low
| AndC
->getValue());
1212 APInt N
= SmallC
->getValue().zext(BigBitSize
) | BigC
->getValue();
1213 Value
*NewVal
= ConstantInt::get(AndC
->getType()->getContext(), N
);
1214 return Builder
.CreateICmp(PredL
, NewAnd
, NewVal
);
1219 // From here on, we only handle:
1220 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1224 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1225 if (PredL
== ICmpInst::ICMP_UGE
|| PredL
== ICmpInst::ICMP_ULE
||
1226 PredR
== ICmpInst::ICMP_UGE
|| PredR
== ICmpInst::ICMP_ULE
||
1227 PredL
== ICmpInst::ICMP_SGE
|| PredL
== ICmpInst::ICMP_SLE
||
1228 PredR
== ICmpInst::ICMP_SGE
|| PredR
== ICmpInst::ICMP_SLE
)
1231 // We can't fold (ugt x, C) & (sgt x, C2).
1232 if (!predicatesFoldable(PredL
, PredR
))
1235 // Ensure that the larger constant is on the RHS.
1237 if (CmpInst::isSigned(PredL
) ||
1238 (ICmpInst::isEquality(PredL
) && CmpInst::isSigned(PredR
)))
1239 ShouldSwap
= LHSC
->getValue().sgt(RHSC
->getValue());
1241 ShouldSwap
= LHSC
->getValue().ugt(RHSC
->getValue());
1244 std::swap(LHS
, RHS
);
1245 std::swap(LHSC
, RHSC
);
1246 std::swap(PredL
, PredR
);
1249 // At this point, we know we have two icmp instructions
1250 // comparing a value against two constants and and'ing the result
1251 // together. Because of the above check, we know that we only have
1252 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1253 // (from the icmp folding check above), that the two constants
1254 // are not equal and that the larger constant is on the RHS
1255 assert(LHSC
!= RHSC
&& "Compares not folded above?");
1259 llvm_unreachable("Unknown integer condition code!");
1260 case ICmpInst::ICMP_NE
:
1263 llvm_unreachable("Unknown integer condition code!");
1264 case ICmpInst::ICMP_ULT
:
1265 // (X != 13 & X u< 14) -> X < 13
1266 if (LHSC
->getValue() == (RHSC
->getValue() - 1))
1267 return Builder
.CreateICmpULT(LHS0
, LHSC
);
1268 if (LHSC
->isZero()) // (X != 0 & X u< C) -> X-1 u< C-1
1269 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(),
1271 break; // (X != 13 & X u< 15) -> no change
1272 case ICmpInst::ICMP_SLT
:
1273 // (X != 13 & X s< 14) -> X < 13
1274 if (LHSC
->getValue() == (RHSC
->getValue() - 1))
1275 return Builder
.CreateICmpSLT(LHS0
, LHSC
);
1276 // (X != INT_MIN & X s< C) -> X-(INT_MIN+1) u< (C-(INT_MIN+1))
1277 if (LHSC
->isMinValue(true))
1278 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(),
1280 break; // (X != 13 & X s< 15) -> no change
1281 case ICmpInst::ICMP_NE
:
1282 // Potential folds for this case should already be handled.
1286 case ICmpInst::ICMP_UGT
:
1289 llvm_unreachable("Unknown integer condition code!");
1290 case ICmpInst::ICMP_NE
:
1291 // (X u> 13 & X != 14) -> X u> 14
1292 if (RHSC
->getValue() == (LHSC
->getValue() + 1))
1293 return Builder
.CreateICmp(PredL
, LHS0
, RHSC
);
1294 // X u> C & X != UINT_MAX -> (X-(C+1)) u< UINT_MAX-(C+1)
1295 if (RHSC
->isMaxValue(false))
1296 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(),
1298 break; // (X u> 13 & X != 15) -> no change
1299 case ICmpInst::ICMP_ULT
: // (X u> 13 & X u< 15) -> (X-14) u< 1
1300 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(),
1304 case ICmpInst::ICMP_SGT
:
1307 llvm_unreachable("Unknown integer condition code!");
1308 case ICmpInst::ICMP_NE
:
1309 // (X s> 13 & X != 14) -> X s> 14
1310 if (RHSC
->getValue() == (LHSC
->getValue() + 1))
1311 return Builder
.CreateICmp(PredL
, LHS0
, RHSC
);
1312 // X s> C & X != INT_MAX -> (X-(C+1)) u< INT_MAX-(C+1)
1313 if (RHSC
->isMaxValue(true))
1314 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(),
1316 break; // (X s> 13 & X != 15) -> no change
1317 case ICmpInst::ICMP_SLT
: // (X s> 13 & X s< 15) -> (X-14) u< 1
1318 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue(), true,
1327 Value
*InstCombiner::foldLogicOfFCmps(FCmpInst
*LHS
, FCmpInst
*RHS
, bool IsAnd
) {
1328 Value
*LHS0
= LHS
->getOperand(0), *LHS1
= LHS
->getOperand(1);
1329 Value
*RHS0
= RHS
->getOperand(0), *RHS1
= RHS
->getOperand(1);
1330 FCmpInst::Predicate PredL
= LHS
->getPredicate(), PredR
= RHS
->getPredicate();
1332 if (LHS0
== RHS1
&& RHS0
== LHS1
) {
1333 // Swap RHS operands to match LHS.
1334 PredR
= FCmpInst::getSwappedPredicate(PredR
);
1335 std::swap(RHS0
, RHS1
);
1338 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1339 // Suppose the relation between x and y is R, where R is one of
1340 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1341 // testing the desired relations.
1343 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1344 // bool(R & CC0) && bool(R & CC1)
1345 // = bool((R & CC0) & (R & CC1))
1346 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1348 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1349 // bool(R & CC0) || bool(R & CC1)
1350 // = bool((R & CC0) | (R & CC1))
1351 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1352 if (LHS0
== RHS0
&& LHS1
== RHS1
) {
1353 unsigned FCmpCodeL
= getFCmpCode(PredL
);
1354 unsigned FCmpCodeR
= getFCmpCode(PredR
);
1355 unsigned NewPred
= IsAnd
? FCmpCodeL
& FCmpCodeR
: FCmpCodeL
| FCmpCodeR
;
1356 return getFCmpValue(NewPred
, LHS0
, LHS1
, Builder
);
1359 if ((PredL
== FCmpInst::FCMP_ORD
&& PredR
== FCmpInst::FCMP_ORD
&& IsAnd
) ||
1360 (PredL
== FCmpInst::FCMP_UNO
&& PredR
== FCmpInst::FCMP_UNO
&& !IsAnd
)) {
1361 if (LHS0
->getType() != RHS0
->getType())
1364 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1365 // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1366 if (match(LHS1
, m_PosZeroFP()) && match(RHS1
, m_PosZeroFP()))
1367 // Ignore the constants because they are obviously not NANs:
1368 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
1369 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
1370 return Builder
.CreateFCmp(PredL
, LHS0
, RHS0
);
1376 /// This a limited reassociation for a special case (see above) where we are
1377 /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1378 /// This could be handled more generally in '-reassociation', but it seems like
1379 /// an unlikely pattern for a large number of logic ops and fcmps.
1380 static Instruction
*reassociateFCmps(BinaryOperator
&BO
,
1381 InstCombiner::BuilderTy
&Builder
) {
1382 Instruction::BinaryOps Opcode
= BO
.getOpcode();
1383 assert((Opcode
== Instruction::And
|| Opcode
== Instruction::Or
) &&
1384 "Expecting and/or op for fcmp transform");
1386 // There are 4 commuted variants of the pattern. Canonicalize operands of this
1387 // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1388 Value
*Op0
= BO
.getOperand(0), *Op1
= BO
.getOperand(1), *X
;
1389 FCmpInst::Predicate Pred
;
1390 if (match(Op1
, m_FCmp(Pred
, m_Value(), m_AnyZeroFP())))
1391 std::swap(Op0
, Op1
);
1393 // Match inner binop and the predicate for combining 2 NAN checks into 1.
1394 BinaryOperator
*BO1
;
1395 FCmpInst::Predicate NanPred
= Opcode
== Instruction::And
? FCmpInst::FCMP_ORD
1396 : FCmpInst::FCMP_UNO
;
1397 if (!match(Op0
, m_FCmp(Pred
, m_Value(X
), m_AnyZeroFP())) || Pred
!= NanPred
||
1398 !match(Op1
, m_BinOp(BO1
)) || BO1
->getOpcode() != Opcode
)
1401 // The inner logic op must have a matching fcmp operand.
1402 Value
*BO10
= BO1
->getOperand(0), *BO11
= BO1
->getOperand(1), *Y
;
1403 if (!match(BO10
, m_FCmp(Pred
, m_Value(Y
), m_AnyZeroFP())) ||
1404 Pred
!= NanPred
|| X
->getType() != Y
->getType())
1405 std::swap(BO10
, BO11
);
1407 if (!match(BO10
, m_FCmp(Pred
, m_Value(Y
), m_AnyZeroFP())) ||
1408 Pred
!= NanPred
|| X
->getType() != Y
->getType())
1411 // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1412 // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z
1413 Value
*NewFCmp
= Builder
.CreateFCmp(Pred
, X
, Y
);
1414 if (auto *NewFCmpInst
= dyn_cast
<FCmpInst
>(NewFCmp
)) {
1415 // Intersect FMF from the 2 source fcmps.
1416 NewFCmpInst
->copyIRFlags(Op0
);
1417 NewFCmpInst
->andIRFlags(BO10
);
1419 return BinaryOperator::Create(Opcode
, NewFCmp
, BO11
);
1422 /// Match De Morgan's Laws:
1423 /// (~A & ~B) == (~(A | B))
1424 /// (~A | ~B) == (~(A & B))
1425 static Instruction
*matchDeMorgansLaws(BinaryOperator
&I
,
1426 InstCombiner::BuilderTy
&Builder
) {
1427 auto Opcode
= I
.getOpcode();
1428 assert((Opcode
== Instruction::And
|| Opcode
== Instruction::Or
) &&
1429 "Trying to match De Morgan's Laws with something other than and/or");
1431 // Flip the logic operation.
1432 Opcode
= (Opcode
== Instruction::And
) ? Instruction::Or
: Instruction::And
;
1435 if (match(I
.getOperand(0), m_OneUse(m_Not(m_Value(A
)))) &&
1436 match(I
.getOperand(1), m_OneUse(m_Not(m_Value(B
)))) &&
1437 !isFreeToInvert(A
, A
->hasOneUse()) &&
1438 !isFreeToInvert(B
, B
->hasOneUse())) {
1439 Value
*AndOr
= Builder
.CreateBinOp(Opcode
, A
, B
, I
.getName() + ".demorgan");
1440 return BinaryOperator::CreateNot(AndOr
);
1446 bool InstCombiner::shouldOptimizeCast(CastInst
*CI
) {
1447 Value
*CastSrc
= CI
->getOperand(0);
1449 // Noop casts and casts of constants should be eliminated trivially.
1450 if (CI
->getSrcTy() == CI
->getDestTy() || isa
<Constant
>(CastSrc
))
1453 // If this cast is paired with another cast that can be eliminated, we prefer
1454 // to have it eliminated.
1455 if (const auto *PrecedingCI
= dyn_cast
<CastInst
>(CastSrc
))
1456 if (isEliminableCastPair(PrecedingCI
, CI
))
1462 /// Fold {and,or,xor} (cast X), C.
1463 static Instruction
*foldLogicCastConstant(BinaryOperator
&Logic
, CastInst
*Cast
,
1464 InstCombiner::BuilderTy
&Builder
) {
1465 Constant
*C
= dyn_cast
<Constant
>(Logic
.getOperand(1));
1469 auto LogicOpc
= Logic
.getOpcode();
1470 Type
*DestTy
= Logic
.getType();
1471 Type
*SrcTy
= Cast
->getSrcTy();
1473 // Move the logic operation ahead of a zext or sext if the constant is
1474 // unchanged in the smaller source type. Performing the logic in a smaller
1475 // type may provide more information to later folds, and the smaller logic
1476 // instruction may be cheaper (particularly in the case of vectors).
1478 if (match(Cast
, m_OneUse(m_ZExt(m_Value(X
))))) {
1479 Constant
*TruncC
= ConstantExpr::getTrunc(C
, SrcTy
);
1480 Constant
*ZextTruncC
= ConstantExpr::getZExt(TruncC
, DestTy
);
1481 if (ZextTruncC
== C
) {
1482 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1483 Value
*NewOp
= Builder
.CreateBinOp(LogicOpc
, X
, TruncC
);
1484 return new ZExtInst(NewOp
, DestTy
);
1488 if (match(Cast
, m_OneUse(m_SExt(m_Value(X
))))) {
1489 Constant
*TruncC
= ConstantExpr::getTrunc(C
, SrcTy
);
1490 Constant
*SextTruncC
= ConstantExpr::getSExt(TruncC
, DestTy
);
1491 if (SextTruncC
== C
) {
1492 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1493 Value
*NewOp
= Builder
.CreateBinOp(LogicOpc
, X
, TruncC
);
1494 return new SExtInst(NewOp
, DestTy
);
1501 /// Fold {and,or,xor} (cast X), Y.
1502 Instruction
*InstCombiner::foldCastedBitwiseLogic(BinaryOperator
&I
) {
1503 auto LogicOpc
= I
.getOpcode();
1504 assert(I
.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1506 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
1507 CastInst
*Cast0
= dyn_cast
<CastInst
>(Op0
);
1511 // This must be a cast from an integer or integer vector source type to allow
1512 // transformation of the logic operation to the source type.
1513 Type
*DestTy
= I
.getType();
1514 Type
*SrcTy
= Cast0
->getSrcTy();
1515 if (!SrcTy
->isIntOrIntVectorTy())
1518 if (Instruction
*Ret
= foldLogicCastConstant(I
, Cast0
, Builder
))
1521 CastInst
*Cast1
= dyn_cast
<CastInst
>(Op1
);
1525 // Both operands of the logic operation are casts. The casts must be of the
1526 // same type for reduction.
1527 auto CastOpcode
= Cast0
->getOpcode();
1528 if (CastOpcode
!= Cast1
->getOpcode() || SrcTy
!= Cast1
->getSrcTy())
1531 Value
*Cast0Src
= Cast0
->getOperand(0);
1532 Value
*Cast1Src
= Cast1
->getOperand(0);
1534 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1535 if (shouldOptimizeCast(Cast0
) && shouldOptimizeCast(Cast1
)) {
1536 Value
*NewOp
= Builder
.CreateBinOp(LogicOpc
, Cast0Src
, Cast1Src
,
1538 return CastInst::Create(CastOpcode
, NewOp
, DestTy
);
1541 // For now, only 'and'/'or' have optimizations after this.
1542 if (LogicOpc
== Instruction::Xor
)
1545 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1546 // cast is otherwise not optimizable. This happens for vector sexts.
1547 ICmpInst
*ICmp0
= dyn_cast
<ICmpInst
>(Cast0Src
);
1548 ICmpInst
*ICmp1
= dyn_cast
<ICmpInst
>(Cast1Src
);
1549 if (ICmp0
&& ICmp1
) {
1550 Value
*Res
= LogicOpc
== Instruction::And
? foldAndOfICmps(ICmp0
, ICmp1
, I
)
1551 : foldOrOfICmps(ICmp0
, ICmp1
, I
);
1553 return CastInst::Create(CastOpcode
, Res
, DestTy
);
1557 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1558 // cast is otherwise not optimizable. This happens for vector sexts.
1559 FCmpInst
*FCmp0
= dyn_cast
<FCmpInst
>(Cast0Src
);
1560 FCmpInst
*FCmp1
= dyn_cast
<FCmpInst
>(Cast1Src
);
1562 if (Value
*R
= foldLogicOfFCmps(FCmp0
, FCmp1
, LogicOpc
== Instruction::And
))
1563 return CastInst::Create(CastOpcode
, R
, DestTy
);
1568 static Instruction
*foldAndToXor(BinaryOperator
&I
,
1569 InstCombiner::BuilderTy
&Builder
) {
1570 assert(I
.getOpcode() == Instruction::And
);
1571 Value
*Op0
= I
.getOperand(0);
1572 Value
*Op1
= I
.getOperand(1);
1575 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1576 // (A | B) & ~(A & B) --> A ^ B
1577 // (A | B) & ~(B & A) --> A ^ B
1578 if (match(&I
, m_BinOp(m_Or(m_Value(A
), m_Value(B
)),
1579 m_Not(m_c_And(m_Deferred(A
), m_Deferred(B
))))))
1580 return BinaryOperator::CreateXor(A
, B
);
1582 // (A | ~B) & (~A | B) --> ~(A ^ B)
1583 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1584 // (~B | A) & (~A | B) --> ~(A ^ B)
1585 // (~B | A) & (B | ~A) --> ~(A ^ B)
1586 if (Op0
->hasOneUse() || Op1
->hasOneUse())
1587 if (match(&I
, m_BinOp(m_c_Or(m_Value(A
), m_Not(m_Value(B
))),
1588 m_c_Or(m_Not(m_Deferred(A
)), m_Deferred(B
)))))
1589 return BinaryOperator::CreateNot(Builder
.CreateXor(A
, B
));
1594 static Instruction
*foldOrToXor(BinaryOperator
&I
,
1595 InstCombiner::BuilderTy
&Builder
) {
1596 assert(I
.getOpcode() == Instruction::Or
);
1597 Value
*Op0
= I
.getOperand(0);
1598 Value
*Op1
= I
.getOperand(1);
1601 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1602 // (A & B) | ~(A | B) --> ~(A ^ B)
1603 // (A & B) | ~(B | A) --> ~(A ^ B)
1604 if (Op0
->hasOneUse() || Op1
->hasOneUse())
1605 if (match(Op0
, m_And(m_Value(A
), m_Value(B
))) &&
1606 match(Op1
, m_Not(m_c_Or(m_Specific(A
), m_Specific(B
)))))
1607 return BinaryOperator::CreateNot(Builder
.CreateXor(A
, B
));
1609 // (A & ~B) | (~A & B) --> A ^ B
1610 // (A & ~B) | (B & ~A) --> A ^ B
1611 // (~B & A) | (~A & B) --> A ^ B
1612 // (~B & A) | (B & ~A) --> A ^ B
1613 if (match(Op0
, m_c_And(m_Value(A
), m_Not(m_Value(B
)))) &&
1614 match(Op1
, m_c_And(m_Not(m_Specific(A
)), m_Specific(B
))))
1615 return BinaryOperator::CreateXor(A
, B
);
1620 /// Return true if a constant shift amount is always less than the specified
1621 /// bit-width. If not, the shift could create poison in the narrower type.
1622 static bool canNarrowShiftAmt(Constant
*C
, unsigned BitWidth
) {
1623 if (auto *ScalarC
= dyn_cast
<ConstantInt
>(C
))
1624 return ScalarC
->getZExtValue() < BitWidth
;
1626 if (C
->getType()->isVectorTy()) {
1627 // Check each element of a constant vector.
1628 unsigned NumElts
= C
->getType()->getVectorNumElements();
1629 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1630 Constant
*Elt
= C
->getAggregateElement(i
);
1633 if (isa
<UndefValue
>(Elt
))
1635 auto *CI
= dyn_cast
<ConstantInt
>(Elt
);
1636 if (!CI
|| CI
->getZExtValue() >= BitWidth
)
1642 // The constant is a constant expression or unknown.
1646 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1647 /// a common zext operand: and (binop (zext X), C), (zext X).
1648 Instruction
*InstCombiner::narrowMaskedBinOp(BinaryOperator
&And
) {
1649 // This transform could also apply to {or, and, xor}, but there are better
1650 // folds for those cases, so we don't expect those patterns here. AShr is not
1651 // handled because it should always be transformed to LShr in this sequence.
1652 // The subtract transform is different because it has a constant on the left.
1653 // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1654 Value
*Op0
= And
.getOperand(0), *Op1
= And
.getOperand(1);
1656 if (!match(Op0
, m_OneUse(m_Add(m_Specific(Op1
), m_Constant(C
)))) &&
1657 !match(Op0
, m_OneUse(m_Mul(m_Specific(Op1
), m_Constant(C
)))) &&
1658 !match(Op0
, m_OneUse(m_LShr(m_Specific(Op1
), m_Constant(C
)))) &&
1659 !match(Op0
, m_OneUse(m_Shl(m_Specific(Op1
), m_Constant(C
)))) &&
1660 !match(Op0
, m_OneUse(m_Sub(m_Constant(C
), m_Specific(Op1
)))))
1664 if (!match(Op1
, m_ZExt(m_Value(X
))) || Op1
->hasNUsesOrMore(3))
1667 Type
*Ty
= And
.getType();
1668 if (!isa
<VectorType
>(Ty
) && !shouldChangeType(Ty
, X
->getType()))
1671 // If we're narrowing a shift, the shift amount must be safe (less than the
1672 // width) in the narrower type. If the shift amount is greater, instsimplify
1673 // usually handles that case, but we can't guarantee/assert it.
1674 Instruction::BinaryOps Opc
= cast
<BinaryOperator
>(Op0
)->getOpcode();
1675 if (Opc
== Instruction::LShr
|| Opc
== Instruction::Shl
)
1676 if (!canNarrowShiftAmt(C
, X
->getType()->getScalarSizeInBits()))
1679 // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1680 // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1681 Value
*NewC
= ConstantExpr::getTrunc(C
, X
->getType());
1682 Value
*NewBO
= Opc
== Instruction::Sub
? Builder
.CreateBinOp(Opc
, NewC
, X
)
1683 : Builder
.CreateBinOp(Opc
, X
, NewC
);
1684 return new ZExtInst(Builder
.CreateAnd(NewBO
, X
), Ty
);
1687 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1688 // here. We should standardize that construct where it is needed or choose some
1689 // other way to ensure that commutated variants of patterns are not missed.
1690 Instruction
*InstCombiner::visitAnd(BinaryOperator
&I
) {
1691 if (Value
*V
= SimplifyAndInst(I
.getOperand(0), I
.getOperand(1),
1692 SQ
.getWithInstruction(&I
)))
1693 return replaceInstUsesWith(I
, V
);
1695 if (SimplifyAssociativeOrCommutative(I
))
1698 if (Instruction
*X
= foldVectorBinop(I
))
1701 // See if we can simplify any instructions used by the instruction whose sole
1702 // purpose is to compute bits we don't care about.
1703 if (SimplifyDemandedInstructionBits(I
))
1706 // Do this before using distributive laws to catch simple and/or/not patterns.
1707 if (Instruction
*Xor
= foldAndToXor(I
, Builder
))
1710 // (A|B)&(A|C) -> A|(B&C) etc
1711 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
1712 return replaceInstUsesWith(I
, V
);
1714 if (Value
*V
= SimplifyBSwap(I
, Builder
))
1715 return replaceInstUsesWith(I
, V
);
1717 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
1719 if (match(Op1
, m_APInt(C
))) {
1721 if (match(Op0
, m_OneUse(m_LogicalShift(m_One(), m_Value(X
)))) &&
1723 // (1 << X) & 1 --> zext(X == 0)
1724 // (1 >> X) & 1 --> zext(X == 0)
1725 Value
*IsZero
= Builder
.CreateICmpEQ(X
, ConstantInt::get(I
.getType(), 0));
1726 return new ZExtInst(IsZero
, I
.getType());
1730 if (match(Op0
, m_OneUse(m_Xor(m_Value(X
), m_APInt(XorC
))))) {
1731 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1732 Constant
*NewC
= ConstantInt::get(I
.getType(), *C
& *XorC
);
1733 Value
*And
= Builder
.CreateAnd(X
, Op1
);
1735 return BinaryOperator::CreateXor(And
, NewC
);
1739 if (match(Op0
, m_OneUse(m_Or(m_Value(X
), m_APInt(OrC
))))) {
1740 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1741 // NOTE: This reduces the number of bits set in the & mask, which
1742 // can expose opportunities for store narrowing for scalars.
1743 // NOTE: SimplifyDemandedBits should have already removed bits from C1
1744 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1745 // above, but this feels safer.
1746 APInt Together
= *C
& *OrC
;
1747 Value
*And
= Builder
.CreateAnd(X
, ConstantInt::get(I
.getType(),
1750 return BinaryOperator::CreateOr(And
, ConstantInt::get(I
.getType(),
1754 // If the mask is only needed on one incoming arm, push the 'and' op up.
1755 if (match(Op0
, m_OneUse(m_Xor(m_Value(X
), m_Value(Y
)))) ||
1756 match(Op0
, m_OneUse(m_Or(m_Value(X
), m_Value(Y
))))) {
1757 APInt
NotAndMask(~(*C
));
1758 BinaryOperator::BinaryOps BinOp
= cast
<BinaryOperator
>(Op0
)->getOpcode();
1759 if (MaskedValueIsZero(X
, NotAndMask
, 0, &I
)) {
1760 // Not masking anything out for the LHS, move mask to RHS.
1761 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1762 Value
*NewRHS
= Builder
.CreateAnd(Y
, Op1
, Y
->getName() + ".masked");
1763 return BinaryOperator::Create(BinOp
, X
, NewRHS
);
1765 if (!isa
<Constant
>(Y
) && MaskedValueIsZero(Y
, NotAndMask
, 0, &I
)) {
1766 // Not masking anything out for the RHS, move mask to LHS.
1767 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1768 Value
*NewLHS
= Builder
.CreateAnd(X
, Op1
, X
->getName() + ".masked");
1769 return BinaryOperator::Create(BinOp
, NewLHS
, Y
);
1775 if (ConstantInt
*AndRHS
= dyn_cast
<ConstantInt
>(Op1
)) {
1776 const APInt
&AndRHSMask
= AndRHS
->getValue();
1778 // Optimize a variety of ((val OP C1) & C2) combinations...
1779 if (BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(Op0
)) {
1780 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1781 // of X and OP behaves well when given trunc(C1) and X.
1782 // TODO: Do this for vectors by using m_APInt isntead of m_ConstantInt.
1783 switch (Op0I
->getOpcode()) {
1786 case Instruction::Xor
:
1787 case Instruction::Or
:
1788 case Instruction::Mul
:
1789 case Instruction::Add
:
1790 case Instruction::Sub
:
1793 // TODO: The one use restrictions could be relaxed a little if the AND
1794 // is going to be removed.
1795 if (match(Op0I
, m_OneUse(m_c_BinOp(m_OneUse(m_ZExt(m_Value(X
))),
1796 m_ConstantInt(C1
))))) {
1797 if (AndRHSMask
.isIntN(X
->getType()->getScalarSizeInBits())) {
1798 auto *TruncC1
= ConstantExpr::getTrunc(C1
, X
->getType());
1800 Value
*Op0LHS
= Op0I
->getOperand(0);
1801 if (isa
<ZExtInst
>(Op0LHS
))
1802 BinOp
= Builder
.CreateBinOp(Op0I
->getOpcode(), X
, TruncC1
);
1804 BinOp
= Builder
.CreateBinOp(Op0I
->getOpcode(), TruncC1
, X
);
1805 auto *TruncC2
= ConstantExpr::getTrunc(AndRHS
, X
->getType());
1806 auto *And
= Builder
.CreateAnd(BinOp
, TruncC2
);
1807 return new ZExtInst(And
, I
.getType());
1812 if (ConstantInt
*Op0CI
= dyn_cast
<ConstantInt
>(Op0I
->getOperand(1)))
1813 if (Instruction
*Res
= OptAndOp(Op0I
, Op0CI
, AndRHS
, I
))
1817 // If this is an integer truncation, and if the source is an 'and' with
1818 // immediate, transform it. This frequently occurs for bitfield accesses.
1820 Value
*X
= nullptr; ConstantInt
*YC
= nullptr;
1821 if (match(Op0
, m_Trunc(m_And(m_Value(X
), m_ConstantInt(YC
))))) {
1822 // Change: and (trunc (and X, YC) to T), C2
1823 // into : and (trunc X to T), trunc(YC) & C2
1824 // This will fold the two constants together, which may allow
1825 // other simplifications.
1826 Value
*NewCast
= Builder
.CreateTrunc(X
, I
.getType(), "and.shrunk");
1827 Constant
*C3
= ConstantExpr::getTrunc(YC
, I
.getType());
1828 C3
= ConstantExpr::getAnd(C3
, AndRHS
);
1829 return BinaryOperator::CreateAnd(NewCast
, C3
);
1834 if (Instruction
*Z
= narrowMaskedBinOp(I
))
1837 if (Instruction
*FoldedLogic
= foldBinOpIntoSelectOrPhi(I
))
1840 if (Instruction
*DeMorgan
= matchDeMorgansLaws(I
, Builder
))
1845 // A & (A ^ B) --> A & ~B
1846 if (match(Op1
, m_OneUse(m_c_Xor(m_Specific(Op0
), m_Value(B
)))))
1847 return BinaryOperator::CreateAnd(Op0
, Builder
.CreateNot(B
));
1848 // (A ^ B) & A --> A & ~B
1849 if (match(Op0
, m_OneUse(m_c_Xor(m_Specific(Op1
), m_Value(B
)))))
1850 return BinaryOperator::CreateAnd(Op1
, Builder
.CreateNot(B
));
1852 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1853 if (match(Op0
, m_Xor(m_Value(A
), m_Value(B
))))
1854 if (match(Op1
, m_Xor(m_Xor(m_Specific(B
), m_Value(C
)), m_Specific(A
))))
1855 if (Op1
->hasOneUse() || isFreeToInvert(C
, C
->hasOneUse()))
1856 return BinaryOperator::CreateAnd(Op0
, Builder
.CreateNot(C
));
1858 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1859 if (match(Op0
, m_Xor(m_Xor(m_Value(A
), m_Value(C
)), m_Value(B
))))
1860 if (match(Op1
, m_Xor(m_Specific(B
), m_Specific(A
))))
1861 if (Op0
->hasOneUse() || isFreeToInvert(C
, C
->hasOneUse()))
1862 return BinaryOperator::CreateAnd(Op1
, Builder
.CreateNot(C
));
1864 // (A | B) & ((~A) ^ B) -> (A & B)
1865 // (A | B) & (B ^ (~A)) -> (A & B)
1866 // (B | A) & ((~A) ^ B) -> (A & B)
1867 // (B | A) & (B ^ (~A)) -> (A & B)
1868 if (match(Op1
, m_c_Xor(m_Not(m_Value(A
)), m_Value(B
))) &&
1869 match(Op0
, m_c_Or(m_Specific(A
), m_Specific(B
))))
1870 return BinaryOperator::CreateAnd(A
, B
);
1872 // ((~A) ^ B) & (A | B) -> (A & B)
1873 // ((~A) ^ B) & (B | A) -> (A & B)
1874 // (B ^ (~A)) & (A | B) -> (A & B)
1875 // (B ^ (~A)) & (B | A) -> (A & B)
1876 if (match(Op0
, m_c_Xor(m_Not(m_Value(A
)), m_Value(B
))) &&
1877 match(Op1
, m_c_Or(m_Specific(A
), m_Specific(B
))))
1878 return BinaryOperator::CreateAnd(A
, B
);
1882 ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(Op0
);
1883 ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(Op1
);
1885 if (Value
*Res
= foldAndOfICmps(LHS
, RHS
, I
))
1886 return replaceInstUsesWith(I
, Res
);
1888 // TODO: Make this recursive; it's a little tricky because an arbitrary
1889 // number of 'and' instructions might have to be created.
1891 if (LHS
&& match(Op1
, m_OneUse(m_And(m_Value(X
), m_Value(Y
))))) {
1892 if (auto *Cmp
= dyn_cast
<ICmpInst
>(X
))
1893 if (Value
*Res
= foldAndOfICmps(LHS
, Cmp
, I
))
1894 return replaceInstUsesWith(I
, Builder
.CreateAnd(Res
, Y
));
1895 if (auto *Cmp
= dyn_cast
<ICmpInst
>(Y
))
1896 if (Value
*Res
= foldAndOfICmps(LHS
, Cmp
, I
))
1897 return replaceInstUsesWith(I
, Builder
.CreateAnd(Res
, X
));
1899 if (RHS
&& match(Op0
, m_OneUse(m_And(m_Value(X
), m_Value(Y
))))) {
1900 if (auto *Cmp
= dyn_cast
<ICmpInst
>(X
))
1901 if (Value
*Res
= foldAndOfICmps(Cmp
, RHS
, I
))
1902 return replaceInstUsesWith(I
, Builder
.CreateAnd(Res
, Y
));
1903 if (auto *Cmp
= dyn_cast
<ICmpInst
>(Y
))
1904 if (Value
*Res
= foldAndOfICmps(Cmp
, RHS
, I
))
1905 return replaceInstUsesWith(I
, Builder
.CreateAnd(Res
, X
));
1909 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(I
.getOperand(0)))
1910 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(I
.getOperand(1)))
1911 if (Value
*Res
= foldLogicOfFCmps(LHS
, RHS
, true))
1912 return replaceInstUsesWith(I
, Res
);
1914 if (Instruction
*FoldedFCmps
= reassociateFCmps(I
, Builder
))
1917 if (Instruction
*CastedAnd
= foldCastedBitwiseLogic(I
))
1920 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1922 if (match(Op0
, m_OneUse(m_SExt(m_Value(A
)))) &&
1923 A
->getType()->isIntOrIntVectorTy(1))
1924 return SelectInst::Create(A
, Op1
, Constant::getNullValue(I
.getType()));
1925 if (match(Op1
, m_OneUse(m_SExt(m_Value(A
)))) &&
1926 A
->getType()->isIntOrIntVectorTy(1))
1927 return SelectInst::Create(A
, Op0
, Constant::getNullValue(I
.getType()));
1929 // and(ashr(subNSW(Y, X), ScalarSizeInBits(Y)-1), X) --> X s> Y ? X : 0.
1933 Type
*Ty
= I
.getType();
1934 if (match(&I
, m_c_And(m_OneUse(m_AShr(m_NSWSub(m_Value(Y
), m_Value(X
)),
1937 *ShAmt
== Ty
->getScalarSizeInBits() - 1) {
1938 Value
*NewICmpInst
= Builder
.CreateICmpSGT(X
, Y
);
1939 return SelectInst::Create(NewICmpInst
, X
, ConstantInt::getNullValue(Ty
));
1946 Instruction
*InstCombiner::matchBSwap(BinaryOperator
&Or
) {
1947 assert(Or
.getOpcode() == Instruction::Or
&& "bswap requires an 'or'");
1948 Value
*Op0
= Or
.getOperand(0), *Op1
= Or
.getOperand(1);
1950 // Look through zero extends.
1951 if (Instruction
*Ext
= dyn_cast
<ZExtInst
>(Op0
))
1952 Op0
= Ext
->getOperand(0);
1954 if (Instruction
*Ext
= dyn_cast
<ZExtInst
>(Op1
))
1955 Op1
= Ext
->getOperand(0);
1957 // (A | B) | C and A | (B | C) -> bswap if possible.
1958 bool OrOfOrs
= match(Op0
, m_Or(m_Value(), m_Value())) ||
1959 match(Op1
, m_Or(m_Value(), m_Value()));
1961 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1962 bool OrOfShifts
= match(Op0
, m_LogicalShift(m_Value(), m_Value())) &&
1963 match(Op1
, m_LogicalShift(m_Value(), m_Value()));
1965 // (A & B) | (C & D) -> bswap if possible.
1966 bool OrOfAnds
= match(Op0
, m_And(m_Value(), m_Value())) &&
1967 match(Op1
, m_And(m_Value(), m_Value()));
1969 // (A << B) | (C & D) -> bswap if possible.
1970 // The bigger pattern here is ((A & C1) << C2) | ((B >> C2) & C1), which is a
1971 // part of the bswap idiom for specific values of C1, C2 (e.g. C1 = 16711935,
1973 // This pattern can occur when the operands of the 'or' are not canonicalized
1974 // for some reason (not having only one use, for example).
1975 bool OrOfAndAndSh
= (match(Op0
, m_LogicalShift(m_Value(), m_Value())) &&
1976 match(Op1
, m_And(m_Value(), m_Value()))) ||
1977 (match(Op0
, m_And(m_Value(), m_Value())) &&
1978 match(Op1
, m_LogicalShift(m_Value(), m_Value())));
1980 if (!OrOfOrs
&& !OrOfShifts
&& !OrOfAnds
&& !OrOfAndAndSh
)
1983 SmallVector
<Instruction
*, 4> Insts
;
1984 if (!recognizeBSwapOrBitReverseIdiom(&Or
, true, false, Insts
))
1986 Instruction
*LastInst
= Insts
.pop_back_val();
1987 LastInst
->removeFromParent();
1989 for (auto *Inst
: Insts
)
1994 /// Transform UB-safe variants of bitwise rotate to the funnel shift intrinsic.
1995 static Instruction
*matchRotate(Instruction
&Or
) {
1996 // TODO: Can we reduce the code duplication between this and the related
1997 // rotate matching code under visitSelect and visitTrunc?
1998 unsigned Width
= Or
.getType()->getScalarSizeInBits();
1999 if (!isPowerOf2_32(Width
))
2002 // First, find an or'd pair of opposite shifts with the same shifted operand:
2003 // or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1)
2004 BinaryOperator
*Or0
, *Or1
;
2005 if (!match(Or
.getOperand(0), m_BinOp(Or0
)) ||
2006 !match(Or
.getOperand(1), m_BinOp(Or1
)))
2009 Value
*ShVal
, *ShAmt0
, *ShAmt1
;
2010 if (!match(Or0
, m_OneUse(m_LogicalShift(m_Value(ShVal
), m_Value(ShAmt0
)))) ||
2011 !match(Or1
, m_OneUse(m_LogicalShift(m_Specific(ShVal
), m_Value(ShAmt1
)))))
2014 BinaryOperator::BinaryOps ShiftOpcode0
= Or0
->getOpcode();
2015 BinaryOperator::BinaryOps ShiftOpcode1
= Or1
->getOpcode();
2016 if (ShiftOpcode0
== ShiftOpcode1
)
2019 // Match the shift amount operands for a rotate pattern. This always matches
2020 // a subtraction on the R operand.
2021 auto matchShiftAmount
= [](Value
*L
, Value
*R
, unsigned Width
) -> Value
* {
2022 // The shift amount may be masked with negation:
2023 // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2025 unsigned Mask
= Width
- 1;
2026 if (match(L
, m_And(m_Value(X
), m_SpecificInt(Mask
))) &&
2027 match(R
, m_And(m_Neg(m_Specific(X
)), m_SpecificInt(Mask
))))
2030 // Similar to above, but the shift amount may be extended after masking,
2031 // so return the extended value as the parameter for the intrinsic.
2032 if (match(L
, m_ZExt(m_And(m_Value(X
), m_SpecificInt(Mask
)))) &&
2033 match(R
, m_And(m_Neg(m_ZExt(m_And(m_Specific(X
), m_SpecificInt(Mask
)))),
2034 m_SpecificInt(Mask
))))
2040 Value
*ShAmt
= matchShiftAmount(ShAmt0
, ShAmt1
, Width
);
2041 bool SubIsOnLHS
= false;
2043 ShAmt
= matchShiftAmount(ShAmt1
, ShAmt0
, Width
);
2049 bool IsFshl
= (!SubIsOnLHS
&& ShiftOpcode0
== BinaryOperator::Shl
) ||
2050 (SubIsOnLHS
&& ShiftOpcode1
== BinaryOperator::Shl
);
2051 Intrinsic::ID IID
= IsFshl
? Intrinsic::fshl
: Intrinsic::fshr
;
2052 Function
*F
= Intrinsic::getDeclaration(Or
.getModule(), IID
, Or
.getType());
2053 return IntrinsicInst::Create(F
, { ShVal
, ShVal
, ShAmt
});
2056 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
2057 static bool areInverseVectorBitmasks(Constant
*C1
, Constant
*C2
) {
2058 unsigned NumElts
= C1
->getType()->getVectorNumElements();
2059 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2060 Constant
*EltC1
= C1
->getAggregateElement(i
);
2061 Constant
*EltC2
= C2
->getAggregateElement(i
);
2062 if (!EltC1
|| !EltC2
)
2065 // One element must be all ones, and the other must be all zeros.
2066 if (!((match(EltC1
, m_Zero()) && match(EltC2
, m_AllOnes())) ||
2067 (match(EltC2
, m_Zero()) && match(EltC1
, m_AllOnes()))))
2073 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
2074 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
2075 /// B, it can be used as the condition operand of a select instruction.
2076 Value
*InstCombiner::getSelectCondition(Value
*A
, Value
*B
) {
2077 // Step 1: We may have peeked through bitcasts in the caller.
2078 // Exit immediately if we don't have (vector) integer types.
2079 Type
*Ty
= A
->getType();
2080 if (!Ty
->isIntOrIntVectorTy() || !B
->getType()->isIntOrIntVectorTy())
2083 // Step 2: We need 0 or all-1's bitmasks.
2084 if (ComputeNumSignBits(A
) != Ty
->getScalarSizeInBits())
2087 // Step 3: If B is the 'not' value of A, we have our answer.
2088 if (match(A
, m_Not(m_Specific(B
)))) {
2089 // If these are scalars or vectors of i1, A can be used directly.
2090 if (Ty
->isIntOrIntVectorTy(1))
2092 return Builder
.CreateTrunc(A
, CmpInst::makeCmpResultType(Ty
));
2095 // If both operands are constants, see if the constants are inverse bitmasks.
2096 Constant
*AConst
, *BConst
;
2097 if (match(A
, m_Constant(AConst
)) && match(B
, m_Constant(BConst
)))
2098 if (AConst
== ConstantExpr::getNot(BConst
))
2099 return Builder
.CreateZExtOrTrunc(A
, CmpInst::makeCmpResultType(Ty
));
2101 // Look for more complex patterns. The 'not' op may be hidden behind various
2102 // casts. Look through sexts and bitcasts to find the booleans.
2105 if (match(A
, m_SExt(m_Value(Cond
))) &&
2106 Cond
->getType()->isIntOrIntVectorTy(1) &&
2107 match(B
, m_OneUse(m_Not(m_Value(NotB
))))) {
2108 NotB
= peekThroughBitcast(NotB
, true);
2109 if (match(NotB
, m_SExt(m_Specific(Cond
))))
2113 // All scalar (and most vector) possibilities should be handled now.
2114 // Try more matches that only apply to non-splat constant vectors.
2115 if (!Ty
->isVectorTy())
2118 // If both operands are xor'd with constants using the same sexted boolean
2119 // operand, see if the constants are inverse bitmasks.
2120 // TODO: Use ConstantExpr::getNot()?
2121 if (match(A
, (m_Xor(m_SExt(m_Value(Cond
)), m_Constant(AConst
)))) &&
2122 match(B
, (m_Xor(m_SExt(m_Specific(Cond
)), m_Constant(BConst
)))) &&
2123 Cond
->getType()->isIntOrIntVectorTy(1) &&
2124 areInverseVectorBitmasks(AConst
, BConst
)) {
2125 AConst
= ConstantExpr::getTrunc(AConst
, CmpInst::makeCmpResultType(Ty
));
2126 return Builder
.CreateXor(Cond
, AConst
);
2131 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2132 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2133 Value
*InstCombiner::matchSelectFromAndOr(Value
*A
, Value
*C
, Value
*B
,
2135 // The potential condition of the select may be bitcasted. In that case, look
2136 // through its bitcast and the corresponding bitcast of the 'not' condition.
2137 Type
*OrigType
= A
->getType();
2138 A
= peekThroughBitcast(A
, true);
2139 B
= peekThroughBitcast(B
, true);
2140 if (Value
*Cond
= getSelectCondition(A
, B
)) {
2141 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2142 // The bitcasts will either all exist or all not exist. The builder will
2143 // not create unnecessary casts if the types already match.
2144 Value
*BitcastC
= Builder
.CreateBitCast(C
, A
->getType());
2145 Value
*BitcastD
= Builder
.CreateBitCast(D
, A
->getType());
2146 Value
*Select
= Builder
.CreateSelect(Cond
, BitcastC
, BitcastD
);
2147 return Builder
.CreateBitCast(Select
, OrigType
);
2153 /// Fold (icmp)|(icmp) if possible.
2154 Value
*InstCombiner::foldOrOfICmps(ICmpInst
*LHS
, ICmpInst
*RHS
,
2155 Instruction
&CxtI
) {
2156 const SimplifyQuery Q
= SQ
.getWithInstruction(&CxtI
);
2158 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
2159 // if K1 and K2 are a one-bit mask.
2160 if (Value
*V
= foldAndOrOfICmpsOfAndWithPow2(LHS
, RHS
, false, CxtI
))
2163 ICmpInst::Predicate PredL
= LHS
->getPredicate(), PredR
= RHS
->getPredicate();
2165 ConstantInt
*LHSC
= dyn_cast
<ConstantInt
>(LHS
->getOperand(1));
2166 ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(RHS
->getOperand(1));
2168 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
2169 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
2170 // The original condition actually refers to the following two ranges:
2171 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
2172 // We can fold these two ranges if:
2173 // 1) C1 and C2 is unsigned greater than C3.
2174 // 2) The two ranges are separated.
2175 // 3) C1 ^ C2 is one-bit mask.
2176 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
2177 // This implies all values in the two ranges differ by exactly one bit.
2179 if ((PredL
== ICmpInst::ICMP_ULT
|| PredL
== ICmpInst::ICMP_ULE
) &&
2180 PredL
== PredR
&& LHSC
&& RHSC
&& LHS
->hasOneUse() && RHS
->hasOneUse() &&
2181 LHSC
->getType() == RHSC
->getType() &&
2182 LHSC
->getValue() == (RHSC
->getValue())) {
2184 Value
*LAdd
= LHS
->getOperand(0);
2185 Value
*RAdd
= RHS
->getOperand(0);
2187 Value
*LAddOpnd
, *RAddOpnd
;
2188 ConstantInt
*LAddC
, *RAddC
;
2189 if (match(LAdd
, m_Add(m_Value(LAddOpnd
), m_ConstantInt(LAddC
))) &&
2190 match(RAdd
, m_Add(m_Value(RAddOpnd
), m_ConstantInt(RAddC
))) &&
2191 LAddC
->getValue().ugt(LHSC
->getValue()) &&
2192 RAddC
->getValue().ugt(LHSC
->getValue())) {
2194 APInt DiffC
= LAddC
->getValue() ^ RAddC
->getValue();
2195 if (LAddOpnd
== RAddOpnd
&& DiffC
.isPowerOf2()) {
2196 ConstantInt
*MaxAddC
= nullptr;
2197 if (LAddC
->getValue().ult(RAddC
->getValue()))
2202 APInt RRangeLow
= -RAddC
->getValue();
2203 APInt RRangeHigh
= RRangeLow
+ LHSC
->getValue();
2204 APInt LRangeLow
= -LAddC
->getValue();
2205 APInt LRangeHigh
= LRangeLow
+ LHSC
->getValue();
2206 APInt LowRangeDiff
= RRangeLow
^ LRangeLow
;
2207 APInt HighRangeDiff
= RRangeHigh
^ LRangeHigh
;
2208 APInt RangeDiff
= LRangeLow
.sgt(RRangeLow
) ? LRangeLow
- RRangeLow
2209 : RRangeLow
- LRangeLow
;
2211 if (LowRangeDiff
.isPowerOf2() && LowRangeDiff
== HighRangeDiff
&&
2212 RangeDiff
.ugt(LHSC
->getValue())) {
2213 Value
*MaskC
= ConstantInt::get(LAddC
->getType(), ~DiffC
);
2215 Value
*NewAnd
= Builder
.CreateAnd(LAddOpnd
, MaskC
);
2216 Value
*NewAdd
= Builder
.CreateAdd(NewAnd
, MaxAddC
);
2217 return Builder
.CreateICmp(LHS
->getPredicate(), NewAdd
, LHSC
);
2223 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2224 if (predicatesFoldable(PredL
, PredR
)) {
2225 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
2226 LHS
->getOperand(1) == RHS
->getOperand(0))
2227 LHS
->swapOperands();
2228 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
2229 LHS
->getOperand(1) == RHS
->getOperand(1)) {
2230 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
2231 unsigned Code
= getICmpCode(LHS
) | getICmpCode(RHS
);
2232 bool IsSigned
= LHS
->isSigned() || RHS
->isSigned();
2233 return getNewICmpValue(Code
, IsSigned
, Op0
, Op1
, Builder
);
2237 // handle (roughly):
2238 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
2239 if (Value
*V
= foldLogOpOfMaskedICmps(LHS
, RHS
, false, Builder
))
2242 Value
*LHS0
= LHS
->getOperand(0), *RHS0
= RHS
->getOperand(0);
2243 if (LHS
->hasOneUse() || RHS
->hasOneUse()) {
2244 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2245 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
2246 Value
*A
= nullptr, *B
= nullptr;
2247 if (PredL
== ICmpInst::ICMP_EQ
&& LHSC
&& LHSC
->isZero()) {
2249 if (PredR
== ICmpInst::ICMP_ULT
&& LHS0
== RHS
->getOperand(1))
2251 else if (PredR
== ICmpInst::ICMP_UGT
&& LHS0
== RHS0
)
2252 A
= RHS
->getOperand(1);
2254 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2255 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
2256 else if (PredR
== ICmpInst::ICMP_EQ
&& RHSC
&& RHSC
->isZero()) {
2258 if (PredL
== ICmpInst::ICMP_ULT
&& RHS0
== LHS
->getOperand(1))
2260 else if (PredL
== ICmpInst::ICMP_UGT
&& LHS0
== RHS0
)
2261 A
= LHS
->getOperand(1);
2264 return Builder
.CreateICmp(
2266 Builder
.CreateAdd(B
, ConstantInt::getSigned(B
->getType(), -1)), A
);
2269 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2270 if (Value
*V
= simplifyRangeCheck(LHS
, RHS
, /*Inverted=*/true))
2273 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2274 if (Value
*V
= simplifyRangeCheck(RHS
, LHS
, /*Inverted=*/true))
2277 if (Value
*V
= foldAndOrOfEqualityCmpsWithConstants(LHS
, RHS
, false, Builder
))
2280 if (Value
*V
= foldIsPowerOf2(LHS
, RHS
, false /* JoinedByAnd */, Builder
))
2284 foldUnsignedUnderflowCheck(LHS
, RHS
, /*IsAnd=*/false, Q
, Builder
))
2287 foldUnsignedUnderflowCheck(RHS
, LHS
, /*IsAnd=*/false, Q
, Builder
))
2290 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
2294 if (LHSC
== RHSC
&& PredL
== PredR
) {
2295 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2296 if (PredL
== ICmpInst::ICMP_NE
&& LHSC
->isZero()) {
2297 Value
*NewOr
= Builder
.CreateOr(LHS0
, RHS0
);
2298 return Builder
.CreateICmp(PredL
, NewOr
, LHSC
);
2302 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
2303 // iff C2 + CA == C1.
2304 if (PredL
== ICmpInst::ICMP_ULT
&& PredR
== ICmpInst::ICMP_EQ
) {
2306 if (match(LHS0
, m_Add(m_Specific(RHS0
), m_ConstantInt(AddC
))))
2307 if (RHSC
->getValue() + AddC
->getValue() == LHSC
->getValue())
2308 return Builder
.CreateICmpULE(LHS0
, LHSC
);
2311 // From here on, we only handle:
2312 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2316 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
2317 if (PredL
== ICmpInst::ICMP_UGE
|| PredL
== ICmpInst::ICMP_ULE
||
2318 PredR
== ICmpInst::ICMP_UGE
|| PredR
== ICmpInst::ICMP_ULE
||
2319 PredL
== ICmpInst::ICMP_SGE
|| PredL
== ICmpInst::ICMP_SLE
||
2320 PredR
== ICmpInst::ICMP_SGE
|| PredR
== ICmpInst::ICMP_SLE
)
2323 // We can't fold (ugt x, C) | (sgt x, C2).
2324 if (!predicatesFoldable(PredL
, PredR
))
2327 // Ensure that the larger constant is on the RHS.
2329 if (CmpInst::isSigned(PredL
) ||
2330 (ICmpInst::isEquality(PredL
) && CmpInst::isSigned(PredR
)))
2331 ShouldSwap
= LHSC
->getValue().sgt(RHSC
->getValue());
2333 ShouldSwap
= LHSC
->getValue().ugt(RHSC
->getValue());
2336 std::swap(LHS
, RHS
);
2337 std::swap(LHSC
, RHSC
);
2338 std::swap(PredL
, PredR
);
2341 // At this point, we know we have two icmp instructions
2342 // comparing a value against two constants and or'ing the result
2343 // together. Because of the above check, we know that we only have
2344 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2345 // icmp folding check above), that the two constants are not
2347 assert(LHSC
!= RHSC
&& "Compares not folded above?");
2351 llvm_unreachable("Unknown integer condition code!");
2352 case ICmpInst::ICMP_EQ
:
2355 llvm_unreachable("Unknown integer condition code!");
2356 case ICmpInst::ICMP_EQ
:
2357 // Potential folds for this case should already be handled.
2359 case ICmpInst::ICMP_UGT
:
2360 // (X == 0 || X u> C) -> (X-1) u>= C
2361 if (LHSC
->isMinValue(false))
2362 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue() + 1,
2364 // (X == 13 | X u> 14) -> no change
2366 case ICmpInst::ICMP_SGT
:
2367 // (X == INT_MIN || X s> C) -> (X-(INT_MIN+1)) u>= C-INT_MIN
2368 if (LHSC
->isMinValue(true))
2369 return insertRangeTest(LHS0
, LHSC
->getValue() + 1, RHSC
->getValue() + 1,
2371 // (X == 13 | X s> 14) -> no change
2375 case ICmpInst::ICMP_ULT
:
2378 llvm_unreachable("Unknown integer condition code!");
2379 case ICmpInst::ICMP_EQ
: // (X u< 13 | X == 14) -> no change
2380 // (X u< C || X == UINT_MAX) => (X-C) u>= UINT_MAX-C
2381 if (RHSC
->isMaxValue(false))
2382 return insertRangeTest(LHS0
, LHSC
->getValue(), RHSC
->getValue(),
2385 case ICmpInst::ICMP_UGT
: // (X u< 13 | X u> 15) -> (X-13) u> 2
2386 assert(!RHSC
->isMaxValue(false) && "Missed icmp simplification");
2387 return insertRangeTest(LHS0
, LHSC
->getValue(), RHSC
->getValue() + 1,
2391 case ICmpInst::ICMP_SLT
:
2394 llvm_unreachable("Unknown integer condition code!");
2395 case ICmpInst::ICMP_EQ
:
2396 // (X s< C || X == INT_MAX) => (X-C) u>= INT_MAX-C
2397 if (RHSC
->isMaxValue(true))
2398 return insertRangeTest(LHS0
, LHSC
->getValue(), RHSC
->getValue(),
2400 // (X s< 13 | X == 14) -> no change
2402 case ICmpInst::ICMP_SGT
: // (X s< 13 | X s> 15) -> (X-13) u> 2
2403 assert(!RHSC
->isMaxValue(true) && "Missed icmp simplification");
2404 return insertRangeTest(LHS0
, LHSC
->getValue(), RHSC
->getValue() + 1, true,
2412 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2413 // here. We should standardize that construct where it is needed or choose some
2414 // other way to ensure that commutated variants of patterns are not missed.
2415 Instruction
*InstCombiner::visitOr(BinaryOperator
&I
) {
2416 if (Value
*V
= SimplifyOrInst(I
.getOperand(0), I
.getOperand(1),
2417 SQ
.getWithInstruction(&I
)))
2418 return replaceInstUsesWith(I
, V
);
2420 if (SimplifyAssociativeOrCommutative(I
))
2423 if (Instruction
*X
= foldVectorBinop(I
))
2426 // See if we can simplify any instructions used by the instruction whose sole
2427 // purpose is to compute bits we don't care about.
2428 if (SimplifyDemandedInstructionBits(I
))
2431 // Do this before using distributive laws to catch simple and/or/not patterns.
2432 if (Instruction
*Xor
= foldOrToXor(I
, Builder
))
2435 // (A&B)|(A&C) -> A&(B|C) etc
2436 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
2437 return replaceInstUsesWith(I
, V
);
2439 if (Value
*V
= SimplifyBSwap(I
, Builder
))
2440 return replaceInstUsesWith(I
, V
);
2442 if (Instruction
*FoldedLogic
= foldBinOpIntoSelectOrPhi(I
))
2445 if (Instruction
*BSwap
= matchBSwap(I
))
2448 if (Instruction
*Rotate
= matchRotate(I
))
2453 if (match(&I
, m_c_Or(m_OneUse(m_Xor(m_Value(X
), m_APInt(CV
))), m_Value(Y
))) &&
2454 !CV
->isAllOnesValue() && MaskedValueIsZero(Y
, *CV
, 0, &I
)) {
2455 // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2456 // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2457 Value
*Or
= Builder
.CreateOr(X
, Y
);
2458 return BinaryOperator::CreateXor(Or
, ConstantInt::get(I
.getType(), *CV
));
2462 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
2463 Value
*A
, *B
, *C
, *D
;
2464 if (match(Op0
, m_And(m_Value(A
), m_Value(C
))) &&
2465 match(Op1
, m_And(m_Value(B
), m_Value(D
)))) {
2466 ConstantInt
*C1
= dyn_cast
<ConstantInt
>(C
);
2467 ConstantInt
*C2
= dyn_cast
<ConstantInt
>(D
);
2468 if (C1
&& C2
) { // (A & C1)|(B & C2)
2469 Value
*V1
= nullptr, *V2
= nullptr;
2470 if ((C1
->getValue() & C2
->getValue()).isNullValue()) {
2471 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2472 // iff (C1&C2) == 0 and (N&~C1) == 0
2473 if (match(A
, m_Or(m_Value(V1
), m_Value(V2
))) &&
2475 MaskedValueIsZero(V2
, ~C1
->getValue(), 0, &I
)) || // (V|N)
2477 MaskedValueIsZero(V1
, ~C1
->getValue(), 0, &I
)))) // (N|V)
2478 return BinaryOperator::CreateAnd(A
,
2479 Builder
.getInt(C1
->getValue()|C2
->getValue()));
2480 // Or commutes, try both ways.
2481 if (match(B
, m_Or(m_Value(V1
), m_Value(V2
))) &&
2483 MaskedValueIsZero(V2
, ~C2
->getValue(), 0, &I
)) || // (V|N)
2485 MaskedValueIsZero(V1
, ~C2
->getValue(), 0, &I
)))) // (N|V)
2486 return BinaryOperator::CreateAnd(B
,
2487 Builder
.getInt(C1
->getValue()|C2
->getValue()));
2489 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2490 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2491 ConstantInt
*C3
= nullptr, *C4
= nullptr;
2492 if (match(A
, m_Or(m_Value(V1
), m_ConstantInt(C3
))) &&
2493 (C3
->getValue() & ~C1
->getValue()).isNullValue() &&
2494 match(B
, m_Or(m_Specific(V1
), m_ConstantInt(C4
))) &&
2495 (C4
->getValue() & ~C2
->getValue()).isNullValue()) {
2496 V2
= Builder
.CreateOr(V1
, ConstantExpr::getOr(C3
, C4
), "bitfield");
2497 return BinaryOperator::CreateAnd(V2
,
2498 Builder
.getInt(C1
->getValue()|C2
->getValue()));
2502 if (C1
->getValue() == ~C2
->getValue()) {
2505 // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
2506 if (match(A
, m_c_Or(m_Value(X
), m_Specific(B
))))
2507 return BinaryOperator::CreateOr(Builder
.CreateAnd(X
, C1
), B
);
2508 // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
2509 if (match(B
, m_c_Or(m_Specific(A
), m_Value(X
))))
2510 return BinaryOperator::CreateOr(Builder
.CreateAnd(X
, C2
), A
);
2512 // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
2513 if (match(A
, m_c_Xor(m_Value(X
), m_Specific(B
))))
2514 return BinaryOperator::CreateXor(Builder
.CreateAnd(X
, C1
), B
);
2515 // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
2516 if (match(B
, m_c_Xor(m_Specific(A
), m_Value(X
))))
2517 return BinaryOperator::CreateXor(Builder
.CreateAnd(X
, C2
), A
);
2521 // Don't try to form a select if it's unlikely that we'll get rid of at
2522 // least one of the operands. A select is generally more expensive than the
2523 // 'or' that it is replacing.
2524 if (Op0
->hasOneUse() || Op1
->hasOneUse()) {
2525 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2526 if (Value
*V
= matchSelectFromAndOr(A
, C
, B
, D
))
2527 return replaceInstUsesWith(I
, V
);
2528 if (Value
*V
= matchSelectFromAndOr(A
, C
, D
, B
))
2529 return replaceInstUsesWith(I
, V
);
2530 if (Value
*V
= matchSelectFromAndOr(C
, A
, B
, D
))
2531 return replaceInstUsesWith(I
, V
);
2532 if (Value
*V
= matchSelectFromAndOr(C
, A
, D
, B
))
2533 return replaceInstUsesWith(I
, V
);
2534 if (Value
*V
= matchSelectFromAndOr(B
, D
, A
, C
))
2535 return replaceInstUsesWith(I
, V
);
2536 if (Value
*V
= matchSelectFromAndOr(B
, D
, C
, A
))
2537 return replaceInstUsesWith(I
, V
);
2538 if (Value
*V
= matchSelectFromAndOr(D
, B
, A
, C
))
2539 return replaceInstUsesWith(I
, V
);
2540 if (Value
*V
= matchSelectFromAndOr(D
, B
, C
, A
))
2541 return replaceInstUsesWith(I
, V
);
2545 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2546 if (match(Op0
, m_Xor(m_Value(A
), m_Value(B
))))
2547 if (match(Op1
, m_Xor(m_Xor(m_Specific(B
), m_Value(C
)), m_Specific(A
))))
2548 return BinaryOperator::CreateOr(Op0
, C
);
2550 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2551 if (match(Op0
, m_Xor(m_Xor(m_Value(A
), m_Value(C
)), m_Value(B
))))
2552 if (match(Op1
, m_Xor(m_Specific(B
), m_Specific(A
))))
2553 return BinaryOperator::CreateOr(Op1
, C
);
2555 // ((B | C) & A) | B -> B | (A & C)
2556 if (match(Op0
, m_And(m_Or(m_Specific(Op1
), m_Value(C
)), m_Value(A
))))
2557 return BinaryOperator::CreateOr(Op1
, Builder
.CreateAnd(A
, C
));
2559 if (Instruction
*DeMorgan
= matchDeMorgansLaws(I
, Builder
))
2562 // Canonicalize xor to the RHS.
2563 bool SwappedForXor
= false;
2564 if (match(Op0
, m_Xor(m_Value(), m_Value()))) {
2565 std::swap(Op0
, Op1
);
2566 SwappedForXor
= true;
2569 // A | ( A ^ B) -> A | B
2570 // A | (~A ^ B) -> A | ~B
2571 // (A & B) | (A ^ B)
2572 if (match(Op1
, m_Xor(m_Value(A
), m_Value(B
)))) {
2573 if (Op0
== A
|| Op0
== B
)
2574 return BinaryOperator::CreateOr(A
, B
);
2576 if (match(Op0
, m_And(m_Specific(A
), m_Specific(B
))) ||
2577 match(Op0
, m_And(m_Specific(B
), m_Specific(A
))))
2578 return BinaryOperator::CreateOr(A
, B
);
2580 if (Op1
->hasOneUse() && match(A
, m_Not(m_Specific(Op0
)))) {
2581 Value
*Not
= Builder
.CreateNot(B
, B
->getName() + ".not");
2582 return BinaryOperator::CreateOr(Not
, Op0
);
2584 if (Op1
->hasOneUse() && match(B
, m_Not(m_Specific(Op0
)))) {
2585 Value
*Not
= Builder
.CreateNot(A
, A
->getName() + ".not");
2586 return BinaryOperator::CreateOr(Not
, Op0
);
2590 // A | ~(A | B) -> A | ~B
2591 // A | ~(A ^ B) -> A | ~B
2592 if (match(Op1
, m_Not(m_Value(A
))))
2593 if (BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(A
))
2594 if ((Op0
== B
->getOperand(0) || Op0
== B
->getOperand(1)) &&
2595 Op1
->hasOneUse() && (B
->getOpcode() == Instruction::Or
||
2596 B
->getOpcode() == Instruction::Xor
)) {
2597 Value
*NotOp
= Op0
== B
->getOperand(0) ? B
->getOperand(1) :
2599 Value
*Not
= Builder
.CreateNot(NotOp
, NotOp
->getName() + ".not");
2600 return BinaryOperator::CreateOr(Not
, Op0
);
2604 std::swap(Op0
, Op1
);
2607 ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(Op0
);
2608 ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(Op1
);
2610 if (Value
*Res
= foldOrOfICmps(LHS
, RHS
, I
))
2611 return replaceInstUsesWith(I
, Res
);
2613 // TODO: Make this recursive; it's a little tricky because an arbitrary
2614 // number of 'or' instructions might have to be created.
2616 if (LHS
&& match(Op1
, m_OneUse(m_Or(m_Value(X
), m_Value(Y
))))) {
2617 if (auto *Cmp
= dyn_cast
<ICmpInst
>(X
))
2618 if (Value
*Res
= foldOrOfICmps(LHS
, Cmp
, I
))
2619 return replaceInstUsesWith(I
, Builder
.CreateOr(Res
, Y
));
2620 if (auto *Cmp
= dyn_cast
<ICmpInst
>(Y
))
2621 if (Value
*Res
= foldOrOfICmps(LHS
, Cmp
, I
))
2622 return replaceInstUsesWith(I
, Builder
.CreateOr(Res
, X
));
2624 if (RHS
&& match(Op0
, m_OneUse(m_Or(m_Value(X
), m_Value(Y
))))) {
2625 if (auto *Cmp
= dyn_cast
<ICmpInst
>(X
))
2626 if (Value
*Res
= foldOrOfICmps(Cmp
, RHS
, I
))
2627 return replaceInstUsesWith(I
, Builder
.CreateOr(Res
, Y
));
2628 if (auto *Cmp
= dyn_cast
<ICmpInst
>(Y
))
2629 if (Value
*Res
= foldOrOfICmps(Cmp
, RHS
, I
))
2630 return replaceInstUsesWith(I
, Builder
.CreateOr(Res
, X
));
2634 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(I
.getOperand(0)))
2635 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(I
.getOperand(1)))
2636 if (Value
*Res
= foldLogicOfFCmps(LHS
, RHS
, false))
2637 return replaceInstUsesWith(I
, Res
);
2639 if (Instruction
*FoldedFCmps
= reassociateFCmps(I
, Builder
))
2642 if (Instruction
*CastedOr
= foldCastedBitwiseLogic(I
))
2645 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2646 if (match(Op0
, m_OneUse(m_SExt(m_Value(A
)))) &&
2647 A
->getType()->isIntOrIntVectorTy(1))
2648 return SelectInst::Create(A
, ConstantInt::getSigned(I
.getType(), -1), Op1
);
2649 if (match(Op1
, m_OneUse(m_SExt(m_Value(A
)))) &&
2650 A
->getType()->isIntOrIntVectorTy(1))
2651 return SelectInst::Create(A
, ConstantInt::getSigned(I
.getType(), -1), Op0
);
2653 // Note: If we've gotten to the point of visiting the outer OR, then the
2654 // inner one couldn't be simplified. If it was a constant, then it won't
2655 // be simplified by a later pass either, so we try swapping the inner/outer
2656 // ORs in the hopes that we'll be able to simplify it this way.
2657 // (X|C) | V --> (X|V) | C
2659 if (Op0
->hasOneUse() && !isa
<ConstantInt
>(Op1
) &&
2660 match(Op0
, m_Or(m_Value(A
), m_ConstantInt(CI
)))) {
2661 Value
*Inner
= Builder
.CreateOr(A
, Op1
);
2662 Inner
->takeName(Op0
);
2663 return BinaryOperator::CreateOr(Inner
, CI
);
2666 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2667 // Since this OR statement hasn't been optimized further yet, we hope
2668 // that this transformation will allow the new ORs to be optimized.
2670 Value
*X
= nullptr, *Y
= nullptr;
2671 if (Op0
->hasOneUse() && Op1
->hasOneUse() &&
2672 match(Op0
, m_Select(m_Value(X
), m_Value(A
), m_Value(B
))) &&
2673 match(Op1
, m_Select(m_Value(Y
), m_Value(C
), m_Value(D
))) && X
== Y
) {
2674 Value
*orTrue
= Builder
.CreateOr(A
, C
);
2675 Value
*orFalse
= Builder
.CreateOr(B
, D
);
2676 return SelectInst::Create(X
, orTrue
, orFalse
);
2680 // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y)-1), X) --> X s> Y ? -1 : X.
2684 Type
*Ty
= I
.getType();
2685 if (match(&I
, m_c_Or(m_OneUse(m_AShr(m_NSWSub(m_Value(Y
), m_Value(X
)),
2688 *ShAmt
== Ty
->getScalarSizeInBits() - 1) {
2689 Value
*NewICmpInst
= Builder
.CreateICmpSGT(X
, Y
);
2690 return SelectInst::Create(NewICmpInst
, ConstantInt::getAllOnesValue(Ty
),
2698 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2699 /// can fold these early and efficiently by morphing an existing instruction.
2700 static Instruction
*foldXorToXor(BinaryOperator
&I
,
2701 InstCombiner::BuilderTy
&Builder
) {
2702 assert(I
.getOpcode() == Instruction::Xor
);
2703 Value
*Op0
= I
.getOperand(0);
2704 Value
*Op1
= I
.getOperand(1);
2707 // There are 4 commuted variants for each of the basic patterns.
2709 // (A & B) ^ (A | B) -> A ^ B
2710 // (A & B) ^ (B | A) -> A ^ B
2711 // (A | B) ^ (A & B) -> A ^ B
2712 // (A | B) ^ (B & A) -> A ^ B
2713 if (match(&I
, m_c_Xor(m_And(m_Value(A
), m_Value(B
)),
2714 m_c_Or(m_Deferred(A
), m_Deferred(B
))))) {
2720 // (A | ~B) ^ (~A | B) -> A ^ B
2721 // (~B | A) ^ (~A | B) -> A ^ B
2722 // (~A | B) ^ (A | ~B) -> A ^ B
2723 // (B | ~A) ^ (A | ~B) -> A ^ B
2724 if (match(&I
, m_Xor(m_c_Or(m_Value(A
), m_Not(m_Value(B
))),
2725 m_c_Or(m_Not(m_Deferred(A
)), m_Deferred(B
))))) {
2731 // (A & ~B) ^ (~A & B) -> A ^ B
2732 // (~B & A) ^ (~A & B) -> A ^ B
2733 // (~A & B) ^ (A & ~B) -> A ^ B
2734 // (B & ~A) ^ (A & ~B) -> A ^ B
2735 if (match(&I
, m_Xor(m_c_And(m_Value(A
), m_Not(m_Value(B
))),
2736 m_c_And(m_Not(m_Deferred(A
)), m_Deferred(B
))))) {
2742 // For the remaining cases we need to get rid of one of the operands.
2743 if (!Op0
->hasOneUse() && !Op1
->hasOneUse())
2746 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2747 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2748 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2749 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2750 // Complexity sorting ensures the not will be on the right side.
2751 if ((match(Op0
, m_Or(m_Value(A
), m_Value(B
))) &&
2752 match(Op1
, m_Not(m_c_And(m_Specific(A
), m_Specific(B
))))) ||
2753 (match(Op0
, m_And(m_Value(A
), m_Value(B
))) &&
2754 match(Op1
, m_Not(m_c_Or(m_Specific(A
), m_Specific(B
))))))
2755 return BinaryOperator::CreateNot(Builder
.CreateXor(A
, B
));
2760 Value
*InstCombiner::foldXorOfICmps(ICmpInst
*LHS
, ICmpInst
*RHS
,
2761 BinaryOperator
&I
) {
2762 assert(I
.getOpcode() == Instruction::Xor
&& I
.getOperand(0) == LHS
&&
2763 I
.getOperand(1) == RHS
&& "Should be 'xor' with these operands");
2765 if (predicatesFoldable(LHS
->getPredicate(), RHS
->getPredicate())) {
2766 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
2767 LHS
->getOperand(1) == RHS
->getOperand(0))
2768 LHS
->swapOperands();
2769 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
2770 LHS
->getOperand(1) == RHS
->getOperand(1)) {
2771 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2772 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
2773 unsigned Code
= getICmpCode(LHS
) ^ getICmpCode(RHS
);
2774 bool IsSigned
= LHS
->isSigned() || RHS
->isSigned();
2775 return getNewICmpValue(Code
, IsSigned
, Op0
, Op1
, Builder
);
2779 // TODO: This can be generalized to compares of non-signbits using
2780 // decomposeBitTestICmp(). It could be enhanced more by using (something like)
2781 // foldLogOpOfMaskedICmps().
2782 ICmpInst::Predicate PredL
= LHS
->getPredicate(), PredR
= RHS
->getPredicate();
2783 Value
*LHS0
= LHS
->getOperand(0), *LHS1
= LHS
->getOperand(1);
2784 Value
*RHS0
= RHS
->getOperand(0), *RHS1
= RHS
->getOperand(1);
2785 if ((LHS
->hasOneUse() || RHS
->hasOneUse()) &&
2786 LHS0
->getType() == RHS0
->getType() &&
2787 LHS0
->getType()->isIntOrIntVectorTy()) {
2788 // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
2789 // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
2790 if ((PredL
== CmpInst::ICMP_SGT
&& match(LHS1
, m_AllOnes()) &&
2791 PredR
== CmpInst::ICMP_SGT
&& match(RHS1
, m_AllOnes())) ||
2792 (PredL
== CmpInst::ICMP_SLT
&& match(LHS1
, m_Zero()) &&
2793 PredR
== CmpInst::ICMP_SLT
&& match(RHS1
, m_Zero()))) {
2794 Value
*Zero
= ConstantInt::getNullValue(LHS0
->getType());
2795 return Builder
.CreateICmpSLT(Builder
.CreateXor(LHS0
, RHS0
), Zero
);
2797 // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
2798 // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
2799 if ((PredL
== CmpInst::ICMP_SGT
&& match(LHS1
, m_AllOnes()) &&
2800 PredR
== CmpInst::ICMP_SLT
&& match(RHS1
, m_Zero())) ||
2801 (PredL
== CmpInst::ICMP_SLT
&& match(LHS1
, m_Zero()) &&
2802 PredR
== CmpInst::ICMP_SGT
&& match(RHS1
, m_AllOnes()))) {
2803 Value
*MinusOne
= ConstantInt::getAllOnesValue(LHS0
->getType());
2804 return Builder
.CreateICmpSGT(Builder
.CreateXor(LHS0
, RHS0
), MinusOne
);
2808 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2809 // into those logic ops. That is, try to turn this into an and-of-icmps
2810 // because we have many folds for that pattern.
2812 // This is based on a truth table definition of xor:
2813 // X ^ Y --> (X | Y) & !(X & Y)
2814 if (Value
*OrICmp
= SimplifyBinOp(Instruction::Or
, LHS
, RHS
, SQ
)) {
2815 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2816 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2817 if (Value
*AndICmp
= SimplifyBinOp(Instruction::And
, LHS
, RHS
, SQ
)) {
2818 // TODO: Independently handle cases where the 'and' side is a constant.
2819 ICmpInst
*X
= nullptr, *Y
= nullptr;
2820 if (OrICmp
== LHS
&& AndICmp
== RHS
) {
2821 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS --> X & !Y
2825 if (OrICmp
== RHS
&& AndICmp
== LHS
) {
2826 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS --> !Y & X
2830 if (X
&& Y
&& (Y
->hasOneUse() || canFreelyInvertAllUsersOf(Y
, &I
))) {
2831 // Invert the predicate of 'Y', thus inverting its output.
2832 Y
->setPredicate(Y
->getInversePredicate());
2833 // So, are there other uses of Y?
2834 if (!Y
->hasOneUse()) {
2835 // We need to adapt other uses of Y though. Get a value that matches
2836 // the original value of Y before inversion. While this increases
2837 // immediate instruction count, we have just ensured that all the
2838 // users are freely-invertible, so that 'not' *will* get folded away.
2839 BuilderTy::InsertPointGuard
Guard(Builder
);
2840 // Set insertion point to right after the Y.
2841 Builder
.SetInsertPoint(Y
->getParent(), ++(Y
->getIterator()));
2842 Value
*NotY
= Builder
.CreateNot(Y
, Y
->getName() + ".not");
2843 // Replace all uses of Y (excluding the one in NotY!) with NotY.
2844 Y
->replaceUsesWithIf(NotY
,
2845 [NotY
](Use
&U
) { return U
.getUser() != NotY
; });
2848 return Builder
.CreateAnd(LHS
, RHS
);
2856 /// If we have a masked merge, in the canonical form of:
2857 /// (assuming that A only has one use.)
2859 /// ((x ^ y) & M) ^ y
2861 /// * If M is inverted:
2863 /// ((x ^ y) & ~M) ^ y
2864 /// We can canonicalize by swapping the final xor operand
2865 /// to eliminate the 'not' of the mask.
2866 /// ((x ^ y) & M) ^ x
2867 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
2868 /// because that shortens the dependency chain and improves analysis:
2869 /// (x & M) | (y & ~M)
2870 static Instruction
*visitMaskedMerge(BinaryOperator
&I
,
2871 InstCombiner::BuilderTy
&Builder
) {
2874 if (!match(&I
, m_c_Xor(m_Value(B
),
2876 m_CombineAnd(m_c_Xor(m_Deferred(B
), m_Value(X
)),
2882 if (match(M
, m_Not(m_Value(NotM
)))) {
2883 // De-invert the mask and swap the value in B part.
2884 Value
*NewA
= Builder
.CreateAnd(D
, NotM
);
2885 return BinaryOperator::CreateXor(NewA
, X
);
2889 if (D
->hasOneUse() && match(M
, m_Constant(C
))) {
2891 Value
*LHS
= Builder
.CreateAnd(X
, C
);
2892 Value
*NotC
= Builder
.CreateNot(C
);
2893 Value
*RHS
= Builder
.CreateAnd(B
, NotC
);
2894 return BinaryOperator::CreateOr(LHS
, RHS
);
2906 static Instruction
*sinkNotIntoXor(BinaryOperator
&I
,
2907 InstCombiner::BuilderTy
&Builder
) {
2909 // FIXME: one-use check is not needed in general, but currently we are unable
2910 // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
2911 if (!match(&I
, m_Not(m_OneUse(m_Xor(m_Value(X
), m_Value(Y
))))))
2914 // We only want to do the transform if it is free to do.
2915 if (isFreeToInvert(X
, X
->hasOneUse())) {
2917 } else if (isFreeToInvert(Y
, Y
->hasOneUse())) {
2922 Value
*NotX
= Builder
.CreateNot(X
, X
->getName() + ".not");
2923 return BinaryOperator::CreateXor(NotX
, Y
, I
.getName() + ".demorgan");
2926 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2927 // here. We should standardize that construct where it is needed or choose some
2928 // other way to ensure that commutated variants of patterns are not missed.
2929 Instruction
*InstCombiner::visitXor(BinaryOperator
&I
) {
2930 if (Value
*V
= SimplifyXorInst(I
.getOperand(0), I
.getOperand(1),
2931 SQ
.getWithInstruction(&I
)))
2932 return replaceInstUsesWith(I
, V
);
2934 if (SimplifyAssociativeOrCommutative(I
))
2937 if (Instruction
*X
= foldVectorBinop(I
))
2940 if (Instruction
*NewXor
= foldXorToXor(I
, Builder
))
2943 // (A&B)^(A&C) -> A&(B^C) etc
2944 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
2945 return replaceInstUsesWith(I
, V
);
2947 // See if we can simplify any instructions used by the instruction whose sole
2948 // purpose is to compute bits we don't care about.
2949 if (SimplifyDemandedInstructionBits(I
))
2952 if (Value
*V
= SimplifyBSwap(I
, Builder
))
2953 return replaceInstUsesWith(I
, V
);
2955 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
2957 // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
2958 // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
2959 // calls in there are unnecessary as SimplifyDemandedInstructionBits should
2960 // have already taken care of those cases.
2962 if (match(&I
, m_c_Xor(m_c_And(m_Not(m_Value(M
)), m_Value()),
2963 m_c_And(m_Deferred(M
), m_Value()))))
2964 return BinaryOperator::CreateOr(Op0
, Op1
);
2966 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2969 // We must eliminate the and/or (one-use) for these transforms to not increase
2970 // the instruction count.
2971 // ~(~X & Y) --> (X | ~Y)
2972 // ~(Y & ~X) --> (X | ~Y)
2973 if (match(&I
, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X
)), m_Value(Y
)))))) {
2974 Value
*NotY
= Builder
.CreateNot(Y
, Y
->getName() + ".not");
2975 return BinaryOperator::CreateOr(X
, NotY
);
2977 // ~(~X | Y) --> (X & ~Y)
2978 // ~(Y | ~X) --> (X & ~Y)
2979 if (match(&I
, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X
)), m_Value(Y
)))))) {
2980 Value
*NotY
= Builder
.CreateNot(Y
, Y
->getName() + ".not");
2981 return BinaryOperator::CreateAnd(X
, NotY
);
2984 if (Instruction
*Xor
= visitMaskedMerge(I
, Builder
))
2987 // Is this a 'not' (~) fed by a binary operator?
2988 BinaryOperator
*NotVal
;
2989 if (match(&I
, m_Not(m_BinOp(NotVal
)))) {
2990 if (NotVal
->getOpcode() == Instruction::And
||
2991 NotVal
->getOpcode() == Instruction::Or
) {
2992 // Apply DeMorgan's Law when inverts are free:
2993 // ~(X & Y) --> (~X | ~Y)
2994 // ~(X | Y) --> (~X & ~Y)
2995 if (isFreeToInvert(NotVal
->getOperand(0),
2996 NotVal
->getOperand(0)->hasOneUse()) &&
2997 isFreeToInvert(NotVal
->getOperand(1),
2998 NotVal
->getOperand(1)->hasOneUse())) {
2999 Value
*NotX
= Builder
.CreateNot(NotVal
->getOperand(0), "notlhs");
3000 Value
*NotY
= Builder
.CreateNot(NotVal
->getOperand(1), "notrhs");
3001 if (NotVal
->getOpcode() == Instruction::And
)
3002 return BinaryOperator::CreateOr(NotX
, NotY
);
3003 return BinaryOperator::CreateAnd(NotX
, NotY
);
3007 // ~(X - Y) --> ~X + Y
3008 if (match(NotVal
, m_Sub(m_Value(X
), m_Value(Y
))))
3009 if (isa
<Constant
>(X
) || NotVal
->hasOneUse())
3010 return BinaryOperator::CreateAdd(Builder
.CreateNot(X
), Y
);
3012 // ~(~X >>s Y) --> (X >>s Y)
3013 if (match(NotVal
, m_AShr(m_Not(m_Value(X
)), m_Value(Y
))))
3014 return BinaryOperator::CreateAShr(X
, Y
);
3016 // If we are inverting a right-shifted constant, we may be able to eliminate
3017 // the 'not' by inverting the constant and using the opposite shift type.
3018 // Canonicalization rules ensure that only a negative constant uses 'ashr',
3019 // but we must check that in case that transform has not fired yet.
3021 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
3023 if (match(NotVal
, m_AShr(m_Constant(C
), m_Value(Y
))) &&
3024 match(C
, m_Negative()))
3025 return BinaryOperator::CreateLShr(ConstantExpr::getNot(C
), Y
);
3027 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
3028 if (match(NotVal
, m_LShr(m_Constant(C
), m_Value(Y
))) &&
3029 match(C
, m_NonNegative()))
3030 return BinaryOperator::CreateAShr(ConstantExpr::getNot(C
), Y
);
3032 // ~(X + C) --> -(C + 1) - X
3033 if (match(Op0
, m_Add(m_Value(X
), m_Constant(C
))))
3034 return BinaryOperator::CreateSub(ConstantExpr::getNeg(AddOne(C
)), X
);
3037 // Use DeMorgan and reassociation to eliminate a 'not' op.
3039 if (match(Op1
, m_Constant(C1
))) {
3041 if (match(Op0
, m_OneUse(m_Or(m_Not(m_Value(X
)), m_Constant(C2
))))) {
3042 // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
3043 Value
*And
= Builder
.CreateAnd(X
, ConstantExpr::getNot(C2
));
3044 return BinaryOperator::CreateXor(And
, ConstantExpr::getNot(C1
));
3046 if (match(Op0
, m_OneUse(m_And(m_Not(m_Value(X
)), m_Constant(C2
))))) {
3047 // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
3048 Value
*Or
= Builder
.CreateOr(X
, ConstantExpr::getNot(C2
));
3049 return BinaryOperator::CreateXor(Or
, ConstantExpr::getNot(C1
));
3053 // not (cmp A, B) = !cmp A, B
3054 CmpInst::Predicate Pred
;
3055 if (match(&I
, m_Not(m_OneUse(m_Cmp(Pred
, m_Value(), m_Value()))))) {
3056 cast
<CmpInst
>(Op0
)->setPredicate(CmpInst::getInversePredicate(Pred
));
3057 return replaceInstUsesWith(I
, Op0
);
3062 if (match(Op1
, m_APInt(RHSC
))) {
3065 if (RHSC
->isSignMask() && match(Op0
, m_Sub(m_APInt(C
), m_Value(X
)))) {
3066 // (C - X) ^ signmask -> (C + signmask - X)
3067 Constant
*NewC
= ConstantInt::get(I
.getType(), *C
+ *RHSC
);
3068 return BinaryOperator::CreateSub(NewC
, X
);
3070 if (RHSC
->isSignMask() && match(Op0
, m_Add(m_Value(X
), m_APInt(C
)))) {
3071 // (X + C) ^ signmask -> (X + C + signmask)
3072 Constant
*NewC
= ConstantInt::get(I
.getType(), *C
+ *RHSC
);
3073 return BinaryOperator::CreateAdd(X
, NewC
);
3076 // (X|C1)^C2 -> X^(C1^C2) iff X&~C1 == 0
3077 if (match(Op0
, m_Or(m_Value(X
), m_APInt(C
))) &&
3078 MaskedValueIsZero(X
, *C
, 0, &I
)) {
3079 Constant
*NewC
= ConstantInt::get(I
.getType(), *C
^ *RHSC
);
3080 Worklist
.Add(cast
<Instruction
>(Op0
));
3082 I
.setOperand(1, NewC
);
3088 if (ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(Op1
)) {
3089 if (BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(Op0
)) {
3090 if (ConstantInt
*Op0CI
= dyn_cast
<ConstantInt
>(Op0I
->getOperand(1))) {
3091 if (Op0I
->getOpcode() == Instruction::LShr
) {
3092 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
3096 if (Op0I
->hasOneUse() &&
3097 (E1
= dyn_cast
<BinaryOperator
>(Op0I
->getOperand(0))) &&
3098 E1
->getOpcode() == Instruction::Xor
&&
3099 (C1
= dyn_cast
<ConstantInt
>(E1
->getOperand(1)))) {
3100 // fold (C1 >> C2) ^ C3
3101 ConstantInt
*C2
= Op0CI
, *C3
= RHSC
;
3102 APInt FoldConst
= C1
->getValue().lshr(C2
->getValue());
3103 FoldConst
^= C3
->getValue();
3104 // Prepare the two operands.
3105 Value
*Opnd0
= Builder
.CreateLShr(E1
->getOperand(0), C2
);
3106 Opnd0
->takeName(Op0I
);
3107 cast
<Instruction
>(Opnd0
)->setDebugLoc(I
.getDebugLoc());
3108 Value
*FoldVal
= ConstantInt::get(Opnd0
->getType(), FoldConst
);
3110 return BinaryOperator::CreateXor(Opnd0
, FoldVal
);
3117 if (Instruction
*FoldedLogic
= foldBinOpIntoSelectOrPhi(I
))
3120 // Y ^ (X | Y) --> X & ~Y
3121 // Y ^ (Y | X) --> X & ~Y
3122 if (match(Op1
, m_OneUse(m_c_Or(m_Value(X
), m_Specific(Op0
)))))
3123 return BinaryOperator::CreateAnd(X
, Builder
.CreateNot(Op0
));
3124 // (X | Y) ^ Y --> X & ~Y
3125 // (Y | X) ^ Y --> X & ~Y
3126 if (match(Op0
, m_OneUse(m_c_Or(m_Value(X
), m_Specific(Op1
)))))
3127 return BinaryOperator::CreateAnd(X
, Builder
.CreateNot(Op1
));
3129 // Y ^ (X & Y) --> ~X & Y
3130 // Y ^ (Y & X) --> ~X & Y
3131 if (match(Op1
, m_OneUse(m_c_And(m_Value(X
), m_Specific(Op0
)))))
3132 return BinaryOperator::CreateAnd(Op0
, Builder
.CreateNot(X
));
3133 // (X & Y) ^ Y --> ~X & Y
3134 // (Y & X) ^ Y --> ~X & Y
3135 // Canonical form is (X & C) ^ C; don't touch that.
3136 // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
3137 // be fixed to prefer that (otherwise we get infinite looping).
3138 if (!match(Op1
, m_Constant()) &&
3139 match(Op0
, m_OneUse(m_c_And(m_Value(X
), m_Specific(Op1
)))))
3140 return BinaryOperator::CreateAnd(Op1
, Builder
.CreateNot(X
));
3143 // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
3144 if (match(&I
, m_c_Xor(m_OneUse(m_Xor(m_Value(A
), m_Value(B
))),
3145 m_OneUse(m_c_Or(m_Deferred(A
), m_Value(C
))))))
3146 return BinaryOperator::CreateXor(
3147 Builder
.CreateAnd(Builder
.CreateNot(A
), C
), B
);
3149 // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
3150 if (match(&I
, m_c_Xor(m_OneUse(m_Xor(m_Value(A
), m_Value(B
))),
3151 m_OneUse(m_c_Or(m_Deferred(B
), m_Value(C
))))))
3152 return BinaryOperator::CreateXor(
3153 Builder
.CreateAnd(Builder
.CreateNot(B
), C
), A
);
3155 // (A & B) ^ (A ^ B) -> (A | B)
3156 if (match(Op0
, m_And(m_Value(A
), m_Value(B
))) &&
3157 match(Op1
, m_c_Xor(m_Specific(A
), m_Specific(B
))))
3158 return BinaryOperator::CreateOr(A
, B
);
3159 // (A ^ B) ^ (A & B) -> (A | B)
3160 if (match(Op0
, m_Xor(m_Value(A
), m_Value(B
))) &&
3161 match(Op1
, m_c_And(m_Specific(A
), m_Specific(B
))))
3162 return BinaryOperator::CreateOr(A
, B
);
3164 // (A & ~B) ^ ~A -> ~(A & B)
3165 // (~B & A) ^ ~A -> ~(A & B)
3166 if (match(Op0
, m_c_And(m_Value(A
), m_Not(m_Value(B
)))) &&
3167 match(Op1
, m_Not(m_Specific(A
))))
3168 return BinaryOperator::CreateNot(Builder
.CreateAnd(A
, B
));
3170 if (auto *LHS
= dyn_cast
<ICmpInst
>(I
.getOperand(0)))
3171 if (auto *RHS
= dyn_cast
<ICmpInst
>(I
.getOperand(1)))
3172 if (Value
*V
= foldXorOfICmps(LHS
, RHS
, I
))
3173 return replaceInstUsesWith(I
, V
);
3175 if (Instruction
*CastedXor
= foldCastedBitwiseLogic(I
))
3178 // Canonicalize a shifty way to code absolute value to the common pattern.
3179 // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
3180 // We're relying on the fact that we only do this transform when the shift has
3181 // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
3183 if (Op0
->hasNUses(2))
3184 std::swap(Op0
, Op1
);
3187 Type
*Ty
= I
.getType();
3188 if (match(Op1
, m_AShr(m_Value(A
), m_APInt(ShAmt
))) &&
3189 Op1
->hasNUses(2) && *ShAmt
== Ty
->getScalarSizeInBits() - 1 &&
3190 match(Op0
, m_OneUse(m_c_Add(m_Specific(A
), m_Specific(Op1
))))) {
3191 // B = ashr i32 A, 31 ; smear the sign bit
3192 // xor (add A, B), B ; add -1 and flip bits if negative
3193 // --> (A < 0) ? -A : A
3194 Value
*Cmp
= Builder
.CreateICmpSLT(A
, ConstantInt::getNullValue(Ty
));
3195 // Copy the nuw/nsw flags from the add to the negate.
3196 auto *Add
= cast
<BinaryOperator
>(Op0
);
3197 Value
*Neg
= Builder
.CreateNeg(A
, "", Add
->hasNoUnsignedWrap(),
3198 Add
->hasNoSignedWrap());
3199 return SelectInst::Create(Cmp
, Neg
, A
);
3202 // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3204 // %notx = xor i32 %x, -1
3205 // %cmp1 = icmp sgt i32 %notx, %y
3206 // %smax = select i1 %cmp1, i32 %notx, i32 %y
3207 // %res = xor i32 %smax, -1
3209 // %noty = xor i32 %y, -1
3210 // %cmp2 = icmp slt %x, %noty
3211 // %res = select i1 %cmp2, i32 %x, i32 %noty
3213 // Same is applicable for smin/umax/umin.
3214 if (match(Op1
, m_AllOnes()) && Op0
->hasOneUse()) {
3216 SelectPatternFlavor SPF
= matchSelectPattern(Op0
, LHS
, RHS
).Flavor
;
3217 if (SelectPatternResult::isMinOrMax(SPF
)) {
3218 // It's possible we get here before the not has been simplified, so make
3219 // sure the input to the not isn't freely invertible.
3220 if (match(LHS
, m_Not(m_Value(X
))) && !isFreeToInvert(X
, X
->hasOneUse())) {
3221 Value
*NotY
= Builder
.CreateNot(RHS
);
3222 return SelectInst::Create(
3223 Builder
.CreateICmp(getInverseMinMaxPred(SPF
), X
, NotY
), X
, NotY
);
3226 // It's possible we get here before the not has been simplified, so make
3227 // sure the input to the not isn't freely invertible.
3228 if (match(RHS
, m_Not(m_Value(Y
))) && !isFreeToInvert(Y
, Y
->hasOneUse())) {
3229 Value
*NotX
= Builder
.CreateNot(LHS
);
3230 return SelectInst::Create(
3231 Builder
.CreateICmp(getInverseMinMaxPred(SPF
), NotX
, Y
), NotX
, Y
);
3234 // If both sides are freely invertible, then we can get rid of the xor
3236 if (isFreeToInvert(LHS
, !LHS
->hasNUsesOrMore(3)) &&
3237 isFreeToInvert(RHS
, !RHS
->hasNUsesOrMore(3))) {
3238 Value
*NotLHS
= Builder
.CreateNot(LHS
);
3239 Value
*NotRHS
= Builder
.CreateNot(RHS
);
3240 return SelectInst::Create(
3241 Builder
.CreateICmp(getInverseMinMaxPred(SPF
), NotLHS
, NotRHS
),
3247 if (Instruction
*NewXor
= sinkNotIntoXor(I
, Builder
))