1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitAnd, visitOr, and visitXor functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
20 #include "llvm/Transforms/Utils/Local.h"
22 using namespace PatternMatch;
24 #define DEBUG_TYPE "instcombine"
26 static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
31 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
35 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
41 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
43 static unsigned getFCmpCode(FCmpInst::Predicate CC) {
44 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
45 "Unexpected FCmp predicate!");
46 // Take advantage of the bit pattern of FCmpInst::Predicate here.
48 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
49 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
50 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
51 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
52 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
53 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
54 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
55 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
56 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
57 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
58 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
59 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
60 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
61 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
62 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
63 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
67 /// This is the complement of getICmpCode, which turns an opcode and two
68 /// operands into either a constant true or false, or a brand new ICmp
69 /// instruction. The sign is passed in to determine which kind of predicate to
70 /// use in the new icmp instruction.
71 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
73 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
76 return Builder->CreateICmp(NewPred, LHS, RHS);
79 /// This is the complement of getFCmpCode, which turns an opcode and two
80 /// operands into either a FCmp instruction, or a true/false constant.
81 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
82 InstCombiner::BuilderTy *Builder) {
83 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
84 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
85 "Unexpected FCmp predicate!");
86 if (Pred == FCmpInst::FCMP_FALSE)
87 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
88 if (Pred == FCmpInst::FCMP_TRUE)
89 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
90 return Builder->CreateFCmp(Pred, LHS, RHS);
93 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
94 /// \param I Binary operator to transform.
95 /// \return Pointer to node that must replace the original binary operator, or
96 /// null pointer if no transformation was made.
97 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
98 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
101 if (I.getType()->isVectorTy())
104 // Can only do bitwise ops.
105 if (!I.isBitwiseLogicOp())
108 Value *OldLHS = I.getOperand(0);
109 Value *OldRHS = I.getOperand(1);
110 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
111 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
112 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
113 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
114 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
115 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
117 if (!IsBswapLHS && !IsBswapRHS)
120 if (!IsBswapLHS && !ConstLHS)
123 if (!IsBswapRHS && !ConstRHS)
126 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
127 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
128 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
129 Builder->getInt(ConstLHS->getValue().byteSwap());
131 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
132 Builder->getInt(ConstRHS->getValue().byteSwap());
134 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
135 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
136 return Builder->CreateCall(F, BinOp);
139 /// This handles expressions of the form ((val OP C1) & C2). Where
140 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
141 Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
144 BinaryOperator &TheAnd) {
145 Value *X = Op->getOperand(0);
146 Constant *Together = nullptr;
148 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
150 switch (Op->getOpcode()) {
152 case Instruction::Xor:
153 if (Op->hasOneUse()) {
154 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
155 Value *And = Builder->CreateAnd(X, AndRHS);
157 return BinaryOperator::CreateXor(And, Together);
160 case Instruction::Or:
161 if (Op->hasOneUse()){
162 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
163 if (TogetherCI && !TogetherCI->isZero()){
164 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
165 // NOTE: This reduces the number of bits set in the & mask, which
166 // can expose opportunities for store narrowing.
167 Together = ConstantExpr::getXor(AndRHS, Together);
168 Value *And = Builder->CreateAnd(X, Together);
170 return BinaryOperator::CreateOr(And, OpRHS);
175 case Instruction::Add:
176 if (Op->hasOneUse()) {
177 // Adding a one to a single bit bit-field should be turned into an XOR
178 // of the bit. First thing to check is to see if this AND is with a
179 // single bit constant.
180 const APInt &AndRHSV = AndRHS->getValue();
182 // If there is only one bit set.
183 if (AndRHSV.isPowerOf2()) {
184 // Ok, at this point, we know that we are masking the result of the
185 // ADD down to exactly one bit. If the constant we are adding has
186 // no bits set below this bit, then we can eliminate the ADD.
187 const APInt& AddRHS = OpRHS->getValue();
189 // Check to see if any bits below the one bit set in AndRHSV are set.
190 if ((AddRHS & (AndRHSV-1)) == 0) {
191 // If not, the only thing that can effect the output of the AND is
192 // the bit specified by AndRHSV. If that bit is set, the effect of
193 // the XOR is to toggle the bit. If it is clear, then the ADD has
195 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
196 TheAnd.setOperand(0, X);
199 // Pull the XOR out of the AND.
200 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
201 NewAnd->takeName(Op);
202 return BinaryOperator::CreateXor(NewAnd, AndRHS);
209 case Instruction::Shl: {
210 // We know that the AND will not produce any of the bits shifted in, so if
211 // the anded constant includes them, clear them now!
213 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
214 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
215 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
216 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
218 if (CI->getValue() == ShlMask)
219 // Masking out bits that the shift already masks.
220 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
222 if (CI != AndRHS) { // Reducing bits set in and.
223 TheAnd.setOperand(1, CI);
228 case Instruction::LShr: {
229 // We know that the AND will not produce any of the bits shifted in, so if
230 // the anded constant includes them, clear them now! This only applies to
231 // unsigned shifts, because a signed shr may bring in set bits!
233 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
234 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
235 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
236 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
238 if (CI->getValue() == ShrMask)
239 // Masking out bits that the shift already masks.
240 return replaceInstUsesWith(TheAnd, Op);
243 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
248 case Instruction::AShr:
250 // See if this is shifting in some sign extension, then masking it out
252 if (Op->hasOneUse()) {
253 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
254 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
255 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
256 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
257 if (C == AndRHS) { // Masking out bits shifted in.
258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
259 // Make the argument unsigned.
260 Value *ShVal = Op->getOperand(0);
261 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
262 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
270 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
271 /// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
272 /// whether to treat V, Lo, and Hi as signed or not.
273 Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
274 bool isSigned, bool Inside) {
275 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
276 "Lo is not <= Hi in range emission code!");
278 Type *Ty = V->getType();
280 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
282 // V >= Min && V < Hi --> V < Hi
283 // V < Min || V >= Hi --> V >= Hi
284 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
285 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
286 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
287 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
290 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
291 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
293 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
294 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
295 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
298 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
299 /// that can be simplified.
300 /// One of A and B is considered the mask. The other is the value. This is
301 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
302 /// only "Mask", then both A and B can be considered masks. If A is the mask,
303 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
304 /// If both A and C are constants, this proof is also easy.
305 /// For the following explanations, we assume that A is the mask.
307 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
308 /// bits of A are set in B.
309 /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
311 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
312 /// bits of A are cleared in B.
313 /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
315 /// "Mixed" declares that (A & B) == C and C might or might not contain any
316 /// number of one bits and zero bits.
317 /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
319 /// "Not" means that in above descriptions "==" should be replaced by "!=".
320 /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
322 /// If the mask A contains a single bit, then the following is equivalent:
323 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
324 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
325 enum MaskedICmpType {
327 AMask_NotAllOnes = 2,
329 BMask_NotAllOnes = 8,
331 Mask_NotAllZeros = 32,
333 AMask_NotMixed = 128,
338 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
340 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
341 ICmpInst::Predicate Pred) {
342 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
343 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
344 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
345 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
346 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
347 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
348 unsigned MaskVal = 0;
349 if (CCst && CCst->isZero()) {
350 // if C is zero, then both A and B qualify as mask
351 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
352 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
354 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
355 : (AMask_AllOnes | AMask_Mixed));
357 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
358 : (BMask_AllOnes | BMask_Mixed));
363 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
364 : (AMask_NotAllOnes | AMask_NotMixed));
366 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
367 : (Mask_AllZeros | AMask_Mixed));
368 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
369 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
373 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
374 : (BMask_NotAllOnes | BMask_NotMixed));
376 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
377 : (Mask_AllZeros | BMask_Mixed));
378 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
379 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
385 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
386 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
387 /// is adjacent to the corresponding normal flag (recording ==), this just
388 /// involves swapping those bits over.
389 static unsigned conjugateICmpMask(unsigned Mask) {
391 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
392 AMask_Mixed | BMask_Mixed))
395 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
396 AMask_NotMixed | BMask_NotMixed))
402 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
403 /// Return the set of pattern classes (from MaskedICmpType) that both LHS and
405 static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
406 Value *&D, Value *&E, ICmpInst *LHS,
408 ICmpInst::Predicate &PredL,
409 ICmpInst::Predicate &PredR) {
410 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
412 // vectors are not (yet?) supported
413 if (LHS->getOperand(0)->getType()->isVectorTy())
416 // Here comes the tricky part:
417 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
418 // and L11 & L12 == L21 & L22. The same goes for RHS.
419 // Now we must find those components L** and R**, that are equal, so
420 // that we can extract the parameters A, B, C, D, and E for the canonical
422 Value *L1 = LHS->getOperand(0);
423 Value *L2 = LHS->getOperand(1);
424 Value *L11, *L12, *L21, *L22;
425 // Check whether the icmp can be decomposed into a bit test.
426 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
427 L21 = L22 = L1 = nullptr;
429 // Look for ANDs in the LHS icmp.
430 if (!L1->getType()->isIntegerTy()) {
431 // You can icmp pointers, for example. They really aren't masks.
433 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
434 // Any icmp can be viewed as being trivially masked; if it allows us to
435 // remove one, it's worth it.
437 L12 = Constant::getAllOnesValue(L1->getType());
440 if (!L2->getType()->isIntegerTy()) {
441 // You can icmp pointers, for example. They really aren't masks.
443 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
445 L22 = Constant::getAllOnesValue(L2->getType());
449 // Bail if LHS was a icmp that can't be decomposed into an equality.
450 if (!ICmpInst::isEquality(PredL))
453 Value *R1 = RHS->getOperand(0);
454 Value *R2 = RHS->getOperand(1);
457 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
458 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
461 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
470 } else if (R1->getType()->isIntegerTy()) {
471 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
472 // As before, model no mask as a trivial mask if it'll let us do an
475 R12 = Constant::getAllOnesValue(R1->getType());
478 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
483 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
491 // Bail if RHS was a icmp that can't be decomposed into an equality.
492 if (!ICmpInst::isEquality(PredR))
495 // Look for ANDs on the right side of the RHS icmp.
496 if (!Ok && R2->getType()->isIntegerTy()) {
497 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
499 R12 = Constant::getAllOnesValue(R2->getType());
502 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
507 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
522 } else if (L12 == A) {
525 } else if (L21 == A) {
528 } else if (L22 == A) {
533 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
534 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
535 return LeftType & RightType;
538 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
539 /// into a single (icmp(A & X) ==/!= Y).
540 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
541 llvm::InstCombiner::BuilderTy *Builder) {
542 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
543 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
545 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
549 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
550 "Expected equality predicates for masked type of icmps.");
552 // In full generality:
553 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
554 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
556 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
557 // equivalent to (icmp (A & X) !Op Y).
559 // Therefore, we can pretend for the rest of this function that we're dealing
560 // with the conjunction, provided we flip the sense of any comparisons (both
561 // input and output).
563 // In most cases we're going to produce an EQ for the "&&" case.
564 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
566 // Convert the masking analysis into its equivalent with negated
568 Mask = conjugateICmpMask(Mask);
571 if (Mask & Mask_AllZeros) {
572 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
573 // -> (icmp eq (A & (B|D)), 0)
574 Value *NewOr = Builder->CreateOr(B, D);
575 Value *NewAnd = Builder->CreateAnd(A, NewOr);
576 // We can't use C as zero because we might actually handle
577 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
578 // with B and D, having a single bit set.
579 Value *Zero = Constant::getNullValue(A->getType());
580 return Builder->CreateICmp(NewCC, NewAnd, Zero);
582 if (Mask & BMask_AllOnes) {
583 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
584 // -> (icmp eq (A & (B|D)), (B|D))
585 Value *NewOr = Builder->CreateOr(B, D);
586 Value *NewAnd = Builder->CreateAnd(A, NewOr);
587 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
589 if (Mask & AMask_AllOnes) {
590 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
591 // -> (icmp eq (A & (B&D)), A)
592 Value *NewAnd1 = Builder->CreateAnd(B, D);
593 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
594 return Builder->CreateICmp(NewCC, NewAnd2, A);
597 // Remaining cases assume at least that B and D are constant, and depend on
598 // their actual values. This isn't strictly necessary, just a "handle the
599 // easy cases for now" decision.
600 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
603 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
607 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
608 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
609 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
610 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
611 // Only valid if one of the masks is a superset of the other (check "B&D" is
612 // the same as either B or D).
613 APInt NewMask = BCst->getValue() & DCst->getValue();
615 if (NewMask == BCst->getValue())
617 else if (NewMask == DCst->getValue())
621 if (Mask & AMask_NotAllOnes) {
622 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
623 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
624 // Only valid if one of the masks is a superset of the other (check "B|D" is
625 // the same as either B or D).
626 APInt NewMask = BCst->getValue() | DCst->getValue();
628 if (NewMask == BCst->getValue())
630 else if (NewMask == DCst->getValue())
634 if (Mask & BMask_Mixed) {
635 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
636 // We already know that B & C == C && D & E == E.
637 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
638 // C and E, which are shared by both the mask B and the mask D, don't
639 // contradict, then we can transform to
640 // -> (icmp eq (A & (B|D)), (C|E))
641 // Currently, we only handle the case of B, C, D, and E being constant.
642 // We can't simply use C and E because we might actually handle
643 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
644 // with B and D, having a single bit set.
645 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
648 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
652 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
654 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
656 // If there is a conflict, we should actually return a false for the
658 if (((BCst->getValue() & DCst->getValue()) &
659 (CCst->getValue() ^ ECst->getValue())) != 0)
660 return ConstantInt::get(LHS->getType(), !IsAnd);
662 Value *NewOr1 = Builder->CreateOr(B, D);
663 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
664 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
665 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
671 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
672 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
673 /// If \p Inverted is true then the check is for the inverted range, e.g.
674 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
675 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
677 // Check the lower range comparison, e.g. x >= 0
678 // InstCombine already ensured that if there is a constant it's on the RHS.
679 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
683 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
684 Cmp0->getPredicate());
686 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
687 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
688 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
691 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
692 Cmp1->getPredicate());
694 Value *Input = Cmp0->getOperand(0);
696 if (Cmp1->getOperand(0) == Input) {
697 // For the upper range compare we have: icmp x, n
698 RangeEnd = Cmp1->getOperand(1);
699 } else if (Cmp1->getOperand(1) == Input) {
700 // For the upper range compare we have: icmp n, x
701 RangeEnd = Cmp1->getOperand(0);
702 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
707 // Check the upper range comparison, e.g. x < n
708 ICmpInst::Predicate NewPred;
710 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
711 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
712 default: return nullptr;
715 // This simplification is only valid if the upper range is not negative.
716 bool IsNegative, IsNotNegative;
717 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
722 NewPred = ICmpInst::getInversePredicate(NewPred);
724 return Builder->CreateICmp(NewPred, Input, RangeEnd);
728 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
730 InstCombiner::BuilderTy *Builder) {
731 Value *X = LHS->getOperand(0);
732 if (X != RHS->getOperand(0))
735 const APInt *C1, *C2;
736 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
737 !match(RHS->getOperand(1), m_APInt(C2)))
740 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
741 ICmpInst::Predicate Pred = LHS->getPredicate();
742 if (Pred != RHS->getPredicate())
744 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
746 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
749 // The larger unsigned constant goes on the right.
753 APInt Xor = *C1 ^ *C2;
754 if (Xor.isPowerOf2()) {
755 // If LHSC and RHSC differ by only one bit, then set that bit in X and
756 // compare against the larger constant:
757 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
758 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
759 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
760 // 'and' because that may lead to smaller codegen from a smaller constant.
761 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
762 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
765 // Special case: get the ordering right when the values wrap around zero.
766 // Ie, we assumed the constants were unsigned when swapping earlier.
767 if (*C1 == 0 && C2->isAllOnesValue())
770 if (*C1 == *C2 - 1) {
771 // (X == 13 || X == 14) --> X - 13 <=u 1
772 // (X != 13 && X != 14) --> X - 13 >u 1
773 // An 'add' is the canonical IR form, so favor that over a 'sub'.
774 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
775 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
776 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
782 /// Fold (icmp)&(icmp) if possible.
783 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
784 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
786 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
787 if (PredicatesFoldable(PredL, PredR)) {
788 if (LHS->getOperand(0) == RHS->getOperand(1) &&
789 LHS->getOperand(1) == RHS->getOperand(0))
791 if (LHS->getOperand(0) == RHS->getOperand(0) &&
792 LHS->getOperand(1) == RHS->getOperand(1)) {
793 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
794 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
795 bool isSigned = LHS->isSigned() || RHS->isSigned();
796 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
800 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
801 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
804 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
805 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
808 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
809 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
812 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
815 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
816 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
817 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
818 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
822 if (LHSC == RHSC && PredL == PredR) {
823 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
824 // where C is a power of 2 or
825 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
826 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
827 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
828 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
829 return Builder->CreateICmp(PredL, NewOr, LHSC);
833 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
834 // where CMAX is the all ones value for the truncated type,
835 // iff the lower bits of C2 and CA are zero.
836 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
839 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
841 // (trunc x) == C1 & (and x, CA) == C2
842 // (and x, CA) == C2 & (trunc x) == C1
843 if (match(RHS0, m_Trunc(m_Value(V))) &&
844 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
847 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
848 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
853 if (SmallC && BigC) {
854 unsigned BigBitSize = BigC->getType()->getBitWidth();
855 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
857 // Check that the low bits are zero.
858 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
859 if ((Low & AndC->getValue()) == 0 && (Low & BigC->getValue()) == 0) {
860 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
861 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
862 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
863 return Builder->CreateICmp(PredL, NewAnd, NewVal);
868 // From here on, we only handle:
869 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
873 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
874 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
875 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
876 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
877 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
880 // We can't fold (ugt x, C) & (sgt x, C2).
881 if (!PredicatesFoldable(PredL, PredR))
884 // Ensure that the larger constant is on the RHS.
886 if (CmpInst::isSigned(PredL) ||
887 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
888 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
890 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
894 std::swap(LHSC, RHSC);
895 std::swap(PredL, PredR);
898 // At this point, we know we have two icmp instructions
899 // comparing a value against two constants and and'ing the result
900 // together. Because of the above check, we know that we only have
901 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
902 // (from the icmp folding check above), that the two constants
903 // are not equal and that the larger constant is on the RHS
904 assert(LHSC != RHSC && "Compares not folded above?");
908 llvm_unreachable("Unknown integer condition code!");
909 case ICmpInst::ICMP_NE:
912 llvm_unreachable("Unknown integer condition code!");
913 case ICmpInst::ICMP_ULT:
914 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
915 return Builder->CreateICmpULT(LHS0, LHSC);
916 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
917 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
919 break; // (X != 13 & X u< 15) -> no change
920 case ICmpInst::ICMP_SLT:
921 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
922 return Builder->CreateICmpSLT(LHS0, LHSC);
923 break; // (X != 13 & X s< 15) -> no change
924 case ICmpInst::ICMP_NE:
925 // Potential folds for this case should already be handled.
929 case ICmpInst::ICMP_UGT:
932 llvm_unreachable("Unknown integer condition code!");
933 case ICmpInst::ICMP_NE:
934 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
935 return Builder->CreateICmp(PredL, LHS0, RHSC);
936 break; // (X u> 13 & X != 15) -> no change
937 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
938 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
942 case ICmpInst::ICMP_SGT:
945 llvm_unreachable("Unknown integer condition code!");
946 case ICmpInst::ICMP_NE:
947 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
948 return Builder->CreateICmp(PredL, LHS0, RHSC);
949 break; // (X s> 13 & X != 15) -> no change
950 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
951 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
960 /// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
961 /// a Value which should already be inserted into the function.
962 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
963 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
964 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
965 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
967 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
968 // Swap RHS operands to match LHS.
969 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
970 std::swap(Op1LHS, Op1RHS);
973 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
974 // Suppose the relation between x and y is R, where R is one of
975 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
976 // testing the desired relations.
978 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
979 // bool(R & CC0) && bool(R & CC1)
980 // = bool((R & CC0) & (R & CC1))
981 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
982 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
983 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
986 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
987 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
988 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
991 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
992 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
993 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
994 // If either of the constants are nans, then the whole thing returns
996 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
997 return Builder->getFalse();
998 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1001 // Handle vector zeros. This occurs because the canonical form of
1002 // "fcmp ord x,x" is "fcmp ord x, 0".
1003 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1004 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1005 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1012 /// Match De Morgan's Laws:
1013 /// (~A & ~B) == (~(A | B))
1014 /// (~A | ~B) == (~(A & B))
1015 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1016 InstCombiner::BuilderTy *Builder) {
1017 auto Opcode = I.getOpcode();
1018 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1019 "Trying to match De Morgan's Laws with something other than and/or");
1020 // Flip the logic operation.
1021 if (Opcode == Instruction::And)
1022 Opcode = Instruction::Or;
1024 Opcode = Instruction::And;
1026 Value *Op0 = I.getOperand(0);
1027 Value *Op1 = I.getOperand(1);
1028 // TODO: Use pattern matchers instead of dyn_cast.
1029 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1030 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1031 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1032 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1033 I.getName() + ".demorgan");
1034 return BinaryOperator::CreateNot(LogicOp);
1040 bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1041 Value *CastSrc = CI->getOperand(0);
1043 // Noop casts and casts of constants should be eliminated trivially.
1044 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1047 // If this cast is paired with another cast that can be eliminated, we prefer
1048 // to have it eliminated.
1049 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1050 if (isEliminableCastPair(PrecedingCI, CI))
1053 // If this is a vector sext from a compare, then we don't want to break the
1054 // idiom where each element of the extended vector is either zero or all ones.
1055 if (CI->getOpcode() == Instruction::SExt &&
1056 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1062 /// Fold {and,or,xor} (cast X), C.
1063 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1064 InstCombiner::BuilderTy *Builder) {
1066 if (!match(Logic.getOperand(1), m_Constant(C)))
1069 auto LogicOpc = Logic.getOpcode();
1070 Type *DestTy = Logic.getType();
1071 Type *SrcTy = Cast->getSrcTy();
1073 // If the first operand is bitcast, move the logic operation ahead of the
1074 // bitcast (do the logic operation in the original type). This can eliminate
1075 // bitcasts and allow combines that would otherwise be impeded by the bitcast.
1077 if (match(Cast, m_BitCast(m_Value(X)))) {
1078 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1079 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, NewConstant);
1080 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1083 // Similarly, move the logic operation ahead of a zext if the constant is
1084 // unchanged in the smaller source type. Performing the logic in a smaller
1085 // type may provide more information to later folds, and the smaller logic
1086 // instruction may be cheaper (particularly in the case of vectors).
1087 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1088 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1089 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1090 if (ZextTruncC == C) {
1091 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1092 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1093 return new ZExtInst(NewOp, DestTy);
1100 /// Fold {and,or,xor} (cast X), Y.
1101 Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
1102 auto LogicOpc = I.getOpcode();
1103 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1106 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1110 // This must be a cast from an integer or integer vector source type to allow
1111 // transformation of the logic operation to the source type.
1112 Type *DestTy = I.getType();
1113 Type *SrcTy = Cast0->getSrcTy();
1114 if (!SrcTy->isIntOrIntVectorTy())
1117 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1120 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1124 // Both operands of the logic operation are casts. The casts must be of the
1125 // same type for reduction.
1126 auto CastOpcode = Cast0->getOpcode();
1127 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1130 Value *Cast0Src = Cast0->getOperand(0);
1131 Value *Cast1Src = Cast1->getOperand(0);
1133 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1134 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1135 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1137 return CastInst::Create(CastOpcode, NewOp, DestTy);
1140 // For now, only 'and'/'or' have optimizations after this.
1141 if (LogicOpc == Instruction::Xor)
1144 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1145 // cast is otherwise not optimizable. This happens for vector sexts.
1146 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1147 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1148 if (ICmp0 && ICmp1) {
1149 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1150 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1152 return CastInst::Create(CastOpcode, Res, DestTy);
1156 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1157 // cast is otherwise not optimizable. This happens for vector sexts.
1158 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1159 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1160 if (FCmp0 && FCmp1) {
1161 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1162 : FoldOrOfFCmps(FCmp0, FCmp1);
1164 return CastInst::Create(CastOpcode, Res, DestTy);
1171 static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1174 // Canonicalize SExt or Not to the LHS
1175 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1176 std::swap(Op0, Op1);
1179 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1181 if (match(Op0, m_SExt(m_Value(X))) &&
1182 X->getType()->getScalarType()->isIntegerTy(1)) {
1183 Value *Zero = Constant::getNullValue(Op1->getType());
1184 return SelectInst::Create(X, Op1, Zero);
1187 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1188 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1189 X->getType()->getScalarType()->isIntegerTy(1)) {
1190 Value *Zero = Constant::getNullValue(Op0->getType());
1191 return SelectInst::Create(X, Zero, Op1);
1197 static Instruction *foldAndToXor(BinaryOperator &I,
1198 InstCombiner::BuilderTy &Builder) {
1199 assert(I.getOpcode() == Instruction::And);
1200 Value *Op0 = I.getOperand(0);
1201 Value *Op1 = I.getOperand(1);
1204 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1205 // (A | B) & ~(A & B) --> A ^ B
1206 // (A | B) & ~(B & A) --> A ^ B
1207 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1208 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1209 return BinaryOperator::CreateXor(A, B);
1211 // (A | ~B) & (~A | B) --> ~(A ^ B)
1212 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1213 // (~B | A) & (~A | B) --> ~(A ^ B)
1214 // (~B | A) & (B | ~A) --> ~(A ^ B)
1215 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1216 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Value(B))))
1217 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1222 static Instruction *foldOrToXor(BinaryOperator &I,
1223 InstCombiner::BuilderTy &Builder) {
1224 assert(I.getOpcode() == Instruction::Or);
1225 Value *Op0 = I.getOperand(0);
1226 Value *Op1 = I.getOperand(1);
1229 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1230 // (A & B) | ~(A | B) --> ~(A ^ B)
1231 // (A & B) | ~(B | A) --> ~(A ^ B)
1232 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1233 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1234 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1236 // (A & ~B) | (~A & B) --> A ^ B
1237 // (A & ~B) | (B & ~A) --> A ^ B
1238 // (~B & A) | (~A & B) --> A ^ B
1239 // (~B & A) | (B & ~A) --> A ^ B
1240 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1241 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1242 return BinaryOperator::CreateXor(A, B);
1247 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1248 // here. We should standardize that construct where it is needed or choose some
1249 // other way to ensure that commutated variants of patterns are not missed.
1250 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1251 bool Changed = SimplifyAssociativeOrCommutative(I);
1252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1254 if (Value *V = SimplifyVectorOp(I))
1255 return replaceInstUsesWith(I, V);
1257 if (Value *V = SimplifyAndInst(Op0, Op1, DL, &TLI, &DT, &AC))
1258 return replaceInstUsesWith(I, V);
1260 // See if we can simplify any instructions used by the instruction whose sole
1261 // purpose is to compute bits we don't care about.
1262 if (SimplifyDemandedInstructionBits(I))
1265 // Do this before using distributive laws to catch simple and/or/not patterns.
1266 if (Instruction *Xor = foldAndToXor(I, *Builder))
1269 // (A|B)&(A|C) -> A|(B&C) etc
1270 if (Value *V = SimplifyUsingDistributiveLaws(I))
1271 return replaceInstUsesWith(I, V);
1273 if (Value *V = SimplifyBSwap(I))
1274 return replaceInstUsesWith(I, V);
1276 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1277 const APInt &AndRHSMask = AndRHS->getValue();
1279 // Optimize a variety of ((val OP C1) & C2) combinations...
1280 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1281 Value *Op0LHS = Op0I->getOperand(0);
1282 Value *Op0RHS = Op0I->getOperand(1);
1283 switch (Op0I->getOpcode()) {
1285 case Instruction::Xor:
1286 case Instruction::Or: {
1287 // If the mask is only needed on one incoming arm, push it up.
1288 if (!Op0I->hasOneUse()) break;
1290 APInt NotAndRHS(~AndRHSMask);
1291 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1292 // Not masking anything out for the LHS, move to RHS.
1293 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1294 Op0RHS->getName()+".masked");
1295 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1297 if (!isa<Constant>(Op0RHS) &&
1298 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1299 // Not masking anything out for the RHS, move to LHS.
1300 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1301 Op0LHS->getName()+".masked");
1302 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1307 case Instruction::Sub:
1309 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1310 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1314 case Instruction::Shl:
1315 case Instruction::LShr:
1316 // (1 << x) & 1 --> zext(x == 0)
1317 // (1 >> x) & 1 --> zext(x == 0)
1318 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1320 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1321 return new ZExtInst(NewICmp, I.getType());
1326 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1327 // of X and OP behaves well when given trunc(C1) and X.
1328 switch (Op0I->getOpcode()) {
1331 case Instruction::Xor:
1332 case Instruction::Or:
1333 case Instruction::Mul:
1334 case Instruction::Add:
1335 case Instruction::Sub:
1338 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
1339 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1340 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1342 if (isa<ZExtInst>(Op0LHS))
1343 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1345 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1346 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1347 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1348 return new ZExtInst(And, I.getType());
1353 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1354 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1358 // If this is an integer truncation, and if the source is an 'and' with
1359 // immediate, transform it. This frequently occurs for bitfield accesses.
1361 Value *X = nullptr; ConstantInt *YC = nullptr;
1362 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1363 // Change: and (trunc (and X, YC) to T), C2
1364 // into : and (trunc X to T), trunc(YC) & C2
1365 // This will fold the two constants together, which may allow
1366 // other simplifications.
1367 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1368 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1369 C3 = ConstantExpr::getAnd(C3, AndRHS);
1370 return BinaryOperator::CreateAnd(NewCast, C3);
1375 if (isa<Constant>(Op1))
1376 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1379 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1383 Value *A = nullptr, *B = nullptr, *C = nullptr;
1384 // A&(A^B) => A & ~B
1386 Value *tmpOp0 = Op0;
1387 Value *tmpOp1 = Op1;
1388 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1389 if (A == Op1 || B == Op1 ) {
1396 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1400 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
1401 // A is originally -1 (or a vector of -1 and undefs), then we enter
1402 // an endless loop. By checking that A is non-constant we ensure that
1403 // we will never get to the loop.
1404 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1405 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1409 // (A&((~A)|B)) -> A&B
1410 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
1411 return BinaryOperator::CreateAnd(A, Op1);
1412 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
1413 return BinaryOperator::CreateAnd(A, Op0);
1415 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1416 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1417 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1418 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1419 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1421 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1422 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1423 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1424 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1425 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1427 // (A | B) & ((~A) ^ B) -> (A & B)
1428 // (A | B) & (B ^ (~A)) -> (A & B)
1429 // (B | A) & ((~A) ^ B) -> (A & B)
1430 // (B | A) & (B ^ (~A)) -> (A & B)
1431 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1432 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1433 return BinaryOperator::CreateAnd(A, B);
1435 // ((~A) ^ B) & (A | B) -> (A & B)
1436 // ((~A) ^ B) & (B | A) -> (A & B)
1437 // (B ^ (~A)) & (A | B) -> (A & B)
1438 // (B ^ (~A)) & (B | A) -> (A & B)
1439 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1440 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
1441 return BinaryOperator::CreateAnd(A, B);
1445 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1446 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1448 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1449 return replaceInstUsesWith(I, Res);
1451 // TODO: Make this recursive; it's a little tricky because an arbitrary
1452 // number of 'and' instructions might have to be created.
1454 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1455 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1456 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1457 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1458 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1459 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1460 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1462 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1463 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1464 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1465 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1466 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1467 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1468 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1472 // If and'ing two fcmp, try combine them into one.
1473 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1474 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1475 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1476 return replaceInstUsesWith(I, Res);
1478 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1481 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1484 return Changed ? &I : nullptr;
1487 /// Given an OR instruction, check to see if this is a bswap idiom. If so,
1488 /// insert the new intrinsic and return it.
1489 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1490 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1492 // Look through zero extends.
1493 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1494 Op0 = Ext->getOperand(0);
1496 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1497 Op1 = Ext->getOperand(0);
1499 // (A | B) | C and A | (B | C) -> bswap if possible.
1500 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1501 match(Op1, m_Or(m_Value(), m_Value()));
1503 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1504 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1505 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1507 // (A & B) | (C & D) -> bswap if possible.
1508 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1509 match(Op1, m_And(m_Value(), m_Value()));
1511 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1514 SmallVector<Instruction*, 4> Insts;
1515 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
1517 Instruction *LastInst = Insts.pop_back_val();
1518 LastInst->removeFromParent();
1520 for (auto *Inst : Insts)
1525 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
1526 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1527 unsigned NumElts = C1->getType()->getVectorNumElements();
1528 for (unsigned i = 0; i != NumElts; ++i) {
1529 Constant *EltC1 = C1->getAggregateElement(i);
1530 Constant *EltC2 = C2->getAggregateElement(i);
1531 if (!EltC1 || !EltC2)
1534 // One element must be all ones, and the other must be all zeros.
1535 // FIXME: Allow undef elements.
1536 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1537 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1543 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1544 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1545 /// B, it can be used as the condition operand of a select instruction.
1546 static Value *getSelectCondition(Value *A, Value *B,
1547 InstCombiner::BuilderTy &Builder) {
1548 // If these are scalars or vectors of i1, A can be used directly.
1549 Type *Ty = A->getType();
1550 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1553 // If A and B are sign-extended, look through the sexts to find the booleans.
1555 if (match(A, m_SExt(m_Value(Cond))) &&
1556 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1557 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1558 m_SExt(m_Not(m_Specific(Cond))))))
1561 // All scalar (and most vector) possibilities should be handled now.
1562 // Try more matches that only apply to non-splat constant vectors.
1563 if (!Ty->isVectorTy())
1566 // If both operands are constants, see if the constants are inverse bitmasks.
1568 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1569 areInverseVectorBitmasks(AC, BC))
1570 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1572 // If both operands are xor'd with constants using the same sexted boolean
1573 // operand, see if the constants are inverse bitmasks.
1574 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1575 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1576 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1577 areInverseVectorBitmasks(AC, BC)) {
1578 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1579 return Builder.CreateXor(Cond, AC);
1584 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
1585 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
1586 static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
1587 InstCombiner::BuilderTy &Builder) {
1588 // The potential condition of the select may be bitcasted. In that case, look
1589 // through its bitcast and the corresponding bitcast of the 'not' condition.
1590 Type *OrigType = A->getType();
1592 if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1593 match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
1598 if (Value *Cond = getSelectCondition(A, B, Builder)) {
1599 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
1600 // The bitcasts will either all exist or all not exist. The builder will
1601 // not create unnecessary casts if the types already match.
1602 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1603 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1604 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1605 return Builder.CreateBitCast(Select, OrigType);
1611 /// Fold (icmp)|(icmp) if possible.
1612 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1613 Instruction *CxtI) {
1614 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1616 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1617 // if K1 and K2 are a one-bit mask.
1618 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1619 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
1621 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero() &&
1622 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
1624 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1625 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1626 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1627 LAnd->getOpcode() == Instruction::And &&
1628 RAnd->getOpcode() == Instruction::And) {
1630 Value *Mask = nullptr;
1631 Value *Masked = nullptr;
1632 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1633 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, &AC, CxtI,
1635 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, &AC, CxtI,
1637 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1638 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1639 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1640 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, &AC,
1642 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, &AC,
1644 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1645 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1649 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1653 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1654 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1655 // The original condition actually refers to the following two ranges:
1656 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1657 // We can fold these two ranges if:
1658 // 1) C1 and C2 is unsigned greater than C3.
1659 // 2) The two ranges are separated.
1660 // 3) C1 ^ C2 is one-bit mask.
1661 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1662 // This implies all values in the two ranges differ by exactly one bit.
1664 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1665 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1666 LHSC->getType() == RHSC->getType() &&
1667 LHSC->getValue() == (RHSC->getValue())) {
1669 Value *LAdd = LHS->getOperand(0);
1670 Value *RAdd = RHS->getOperand(0);
1672 Value *LAddOpnd, *RAddOpnd;
1673 ConstantInt *LAddC, *RAddC;
1674 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1675 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1676 LAddC->getValue().ugt(LHSC->getValue()) &&
1677 RAddC->getValue().ugt(LHSC->getValue())) {
1679 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1680 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1681 ConstantInt *MaxAddC = nullptr;
1682 if (LAddC->getValue().ult(RAddC->getValue()))
1687 APInt RRangeLow = -RAddC->getValue();
1688 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1689 APInt LRangeLow = -LAddC->getValue();
1690 APInt LRangeHigh = LRangeLow + LHSC->getValue();
1691 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1692 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1693 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1694 : RRangeLow - LRangeLow;
1696 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1697 RangeDiff.ugt(LHSC->getValue())) {
1698 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
1700 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1701 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1702 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
1708 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1709 if (PredicatesFoldable(PredL, PredR)) {
1710 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1711 LHS->getOperand(1) == RHS->getOperand(0))
1712 LHS->swapOperands();
1713 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1714 LHS->getOperand(1) == RHS->getOperand(1)) {
1715 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1716 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1717 bool isSigned = LHS->isSigned() || RHS->isSigned();
1718 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1722 // handle (roughly):
1723 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1724 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1727 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
1728 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1729 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1730 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1731 Value *A = nullptr, *B = nullptr;
1732 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
1734 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1736 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
1737 A = RHS->getOperand(1);
1739 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1740 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1741 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
1743 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1745 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
1746 A = LHS->getOperand(1);
1749 return Builder->CreateICmp(
1751 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1754 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1755 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1758 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1759 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1762 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1765 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1769 if (LHSC == RHSC && PredL == PredR) {
1770 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1771 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
1772 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
1773 return Builder->CreateICmp(PredL, NewOr, LHSC);
1777 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1778 // iff C2 + CA == C1.
1779 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1781 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
1782 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
1783 return Builder->CreateICmpULE(LHS0, LHSC);
1786 // From here on, we only handle:
1787 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1791 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1792 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1793 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1794 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1795 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
1798 // We can't fold (ugt x, C) | (sgt x, C2).
1799 if (!PredicatesFoldable(PredL, PredR))
1802 // Ensure that the larger constant is on the RHS.
1804 if (CmpInst::isSigned(PredL) ||
1805 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
1806 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
1808 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
1811 std::swap(LHS, RHS);
1812 std::swap(LHSC, RHSC);
1813 std::swap(PredL, PredR);
1816 // At this point, we know we have two icmp instructions
1817 // comparing a value against two constants and or'ing the result
1818 // together. Because of the above check, we know that we only have
1819 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1820 // icmp folding check above), that the two constants are not
1822 assert(LHSC != RHSC && "Compares not folded above?");
1826 llvm_unreachable("Unknown integer condition code!");
1827 case ICmpInst::ICMP_EQ:
1830 llvm_unreachable("Unknown integer condition code!");
1831 case ICmpInst::ICMP_EQ:
1832 // Potential folds for this case should already be handled.
1834 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1835 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1837 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1838 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1839 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1843 case ICmpInst::ICMP_NE:
1846 llvm_unreachable("Unknown integer condition code!");
1847 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1848 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1849 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1851 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1852 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1853 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1854 return Builder->getTrue();
1856 case ICmpInst::ICMP_ULT:
1859 llvm_unreachable("Unknown integer condition code!");
1860 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1862 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1863 // If RHSC is [us]MAXINT, it is always false. Not handling
1864 // this can cause overflow.
1865 if (RHSC->isMaxValue(false))
1867 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1869 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1870 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1874 case ICmpInst::ICMP_SLT:
1877 llvm_unreachable("Unknown integer condition code!");
1878 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1880 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1881 // If RHSC is [us]MAXINT, it is always false. Not handling
1882 // this can cause overflow.
1883 if (RHSC->isMaxValue(true))
1885 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
1887 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1888 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1892 case ICmpInst::ICMP_UGT:
1895 llvm_unreachable("Unknown integer condition code!");
1896 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1897 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1899 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1900 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1901 return Builder->getTrue();
1904 case ICmpInst::ICMP_SGT:
1907 llvm_unreachable("Unknown integer condition code!");
1908 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1909 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1911 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1912 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1913 return Builder->getTrue();
1920 /// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1921 /// a Value which should already be inserted into the function.
1922 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1923 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1924 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1925 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1927 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1928 // Swap RHS operands to match LHS.
1929 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1930 std::swap(Op1LHS, Op1RHS);
1933 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1934 // This is a similar transformation to the one in FoldAndOfFCmps.
1936 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1937 // bool(R & CC0) || bool(R & CC1)
1938 // = bool((R & CC0) | (R & CC1))
1939 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1940 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1941 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1944 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1945 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1946 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1947 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1948 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1949 // If either of the constants are nans, then the whole thing returns
1951 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1952 return Builder->getTrue();
1954 // Otherwise, no need to compare the two constants, compare the
1956 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1959 // Handle vector zeros. This occurs because the canonical form of
1960 // "fcmp uno x,x" is "fcmp uno x, 0".
1961 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1962 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1963 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1971 /// This helper function folds:
1973 /// ((A | B) & C1) | (B & C2)
1979 /// when the XOR of the two constants is "all ones" (-1).
1980 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1981 Value *A, Value *B, Value *C) {
1982 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1983 if (!CI1) return nullptr;
1985 Value *V1 = nullptr;
1986 ConstantInt *CI2 = nullptr;
1987 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
1989 APInt Xor = CI1->getValue() ^ CI2->getValue();
1990 if (!Xor.isAllOnesValue()) return nullptr;
1992 if (V1 == A || V1 == B) {
1993 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1994 return BinaryOperator::CreateOr(NewOp, V1);
2000 /// \brief This helper function folds:
2002 /// ((A | B) & C1) ^ (B & C2)
2008 /// when the XOR of the two constants is "all ones" (-1).
2009 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2010 Value *A, Value *B, Value *C) {
2011 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2015 Value *V1 = nullptr;
2016 ConstantInt *CI2 = nullptr;
2017 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2020 APInt Xor = CI1->getValue() ^ CI2->getValue();
2021 if (!Xor.isAllOnesValue())
2024 if (V1 == A || V1 == B) {
2025 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2026 return BinaryOperator::CreateXor(NewOp, V1);
2032 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2033 // here. We should standardize that construct where it is needed or choose some
2034 // other way to ensure that commutated variants of patterns are not missed.
2035 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2036 bool Changed = SimplifyAssociativeOrCommutative(I);
2037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2039 if (Value *V = SimplifyVectorOp(I))
2040 return replaceInstUsesWith(I, V);
2042 if (Value *V = SimplifyOrInst(Op0, Op1, DL, &TLI, &DT, &AC))
2043 return replaceInstUsesWith(I, V);
2045 // See if we can simplify any instructions used by the instruction whose sole
2046 // purpose is to compute bits we don't care about.
2047 if (SimplifyDemandedInstructionBits(I))
2050 // Do this before using distributive laws to catch simple and/or/not patterns.
2051 if (Instruction *Xor = foldOrToXor(I, *Builder))
2054 // (A&B)|(A&C) -> A&(B|C) etc
2055 if (Value *V = SimplifyUsingDistributiveLaws(I))
2056 return replaceInstUsesWith(I, V);
2058 if (Value *V = SimplifyBSwap(I))
2059 return replaceInstUsesWith(I, V);
2061 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2062 ConstantInt *C1 = nullptr; Value *X = nullptr;
2063 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2064 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2066 Value *Or = Builder->CreateOr(X, RHS);
2068 return BinaryOperator::CreateXor(Or,
2069 Builder->getInt(C1->getValue() & ~RHS->getValue()));
2073 if (isa<Constant>(Op1))
2074 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2077 // Given an OR instruction, check to see if this is a bswap.
2078 if (Instruction *BSwap = MatchBSwap(I))
2084 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2085 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2086 MaskedValueIsZero(Op1, *C, 0, &I)) {
2087 Value *NOr = Builder->CreateOr(A, Op1);
2089 return BinaryOperator::CreateXor(NOr,
2090 ConstantInt::get(NOr->getType(), *C));
2093 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2094 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2095 MaskedValueIsZero(Op0, *C, 0, &I)) {
2096 Value *NOr = Builder->CreateOr(A, Op0);
2098 return BinaryOperator::CreateXor(NOr,
2099 ConstantInt::get(NOr->getType(), *C));
2105 // ((~A & B) | A) -> (A | B)
2106 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2107 return BinaryOperator::CreateOr(A, Op1);
2108 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2109 return BinaryOperator::CreateOr(Op0, A);
2111 // ((A & B) | ~A) -> (~A | B)
2112 // The NOT is guaranteed to be in the RHS by complexity ordering.
2113 if (match(Op1, m_Not(m_Value(A))) &&
2114 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2115 return BinaryOperator::CreateOr(Op1, B);
2118 Value *C = nullptr, *D = nullptr;
2119 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2120 match(Op1, m_And(m_Value(B), m_Value(D)))) {
2121 Value *V1 = nullptr, *V2 = nullptr;
2122 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2123 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
2124 if (C1 && C2) { // (A & C1)|(B & C2)
2125 if ((C1->getValue() & C2->getValue()) == 0) {
2126 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2127 // iff (C1&C2) == 0 and (N&~C1) == 0
2128 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2130 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2132 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
2133 return BinaryOperator::CreateAnd(A,
2134 Builder->getInt(C1->getValue()|C2->getValue()));
2135 // Or commutes, try both ways.
2136 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2138 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2140 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
2141 return BinaryOperator::CreateAnd(B,
2142 Builder->getInt(C1->getValue()|C2->getValue()));
2144 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2145 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2146 ConstantInt *C3 = nullptr, *C4 = nullptr;
2147 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2148 (C3->getValue() & ~C1->getValue()) == 0 &&
2149 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2150 (C4->getValue() & ~C2->getValue()) == 0) {
2151 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2152 return BinaryOperator::CreateAnd(V2,
2153 Builder->getInt(C1->getValue()|C2->getValue()));
2158 // Don't try to form a select if it's unlikely that we'll get rid of at
2159 // least one of the operands. A select is generally more expensive than the
2160 // 'or' that it is replacing.
2161 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2162 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2163 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2164 return replaceInstUsesWith(I, V);
2165 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2166 return replaceInstUsesWith(I, V);
2167 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2168 return replaceInstUsesWith(I, V);
2169 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2170 return replaceInstUsesWith(I, V);
2171 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2172 return replaceInstUsesWith(I, V);
2173 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2174 return replaceInstUsesWith(I, V);
2175 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2176 return replaceInstUsesWith(I, V);
2177 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2178 return replaceInstUsesWith(I, V);
2181 // ((A|B)&1)|(B&-2) -> (A&1) | B
2182 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2183 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2184 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2185 if (Ret) return Ret;
2187 // (B&-2)|((A|B)&1) -> (A&1) | B
2188 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2189 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2190 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2191 if (Ret) return Ret;
2193 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2194 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2195 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2196 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2197 if (Ret) return Ret;
2199 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2200 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2201 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2202 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2203 if (Ret) return Ret;
2207 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2208 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2209 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2210 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2211 return BinaryOperator::CreateOr(Op0, C);
2213 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2214 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2215 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2216 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2217 return BinaryOperator::CreateOr(Op1, C);
2219 // ((B | C) & A) | B -> B | (A & C)
2220 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2221 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2223 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2226 // Canonicalize xor to the RHS.
2227 bool SwappedForXor = false;
2228 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2229 std::swap(Op0, Op1);
2230 SwappedForXor = true;
2233 // A | ( A ^ B) -> A | B
2234 // A | (~A ^ B) -> A | ~B
2235 // (A & B) | (A ^ B)
2236 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2237 if (Op0 == A || Op0 == B)
2238 return BinaryOperator::CreateOr(A, B);
2240 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2241 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2242 return BinaryOperator::CreateOr(A, B);
2244 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2245 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2246 return BinaryOperator::CreateOr(Not, Op0);
2248 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2249 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2250 return BinaryOperator::CreateOr(Not, Op0);
2254 // A | ~(A | B) -> A | ~B
2255 // A | ~(A ^ B) -> A | ~B
2256 if (match(Op1, m_Not(m_Value(A))))
2257 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2258 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2259 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2260 B->getOpcode() == Instruction::Xor)) {
2261 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2263 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2264 return BinaryOperator::CreateOr(Not, Op0);
2267 // (A & B) | (~A ^ B) -> (~A ^ B)
2268 // (A & B) | (B ^ ~A) -> (~A ^ B)
2269 // (B & A) | (~A ^ B) -> (~A ^ B)
2270 // (B & A) | (B ^ ~A) -> (~A ^ B)
2271 // The match order is important: match the xor first because the 'not'
2272 // operation defines 'A'. We do not need to match the xor as Op0 because the
2273 // xor was canonicalized to Op1 above.
2274 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2275 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
2276 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2279 std::swap(Op0, Op1);
2282 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2283 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2285 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2286 return replaceInstUsesWith(I, Res);
2288 // TODO: Make this recursive; it's a little tricky because an arbitrary
2289 // number of 'or' instructions might have to be created.
2291 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2292 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2293 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2294 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2295 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2296 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2297 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2299 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2300 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2301 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2302 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2303 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2304 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2305 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2309 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2310 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2311 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2312 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2313 return replaceInstUsesWith(I, Res);
2315 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2318 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2319 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2320 A->getType()->getScalarType()->isIntegerTy(1))
2321 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2322 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2323 A->getType()->getScalarType()->isIntegerTy(1))
2324 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2326 // Note: If we've gotten to the point of visiting the outer OR, then the
2327 // inner one couldn't be simplified. If it was a constant, then it won't
2328 // be simplified by a later pass either, so we try swapping the inner/outer
2329 // ORs in the hopes that we'll be able to simplify it this way.
2330 // (X|C) | V --> (X|V) | C
2332 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2333 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2334 Value *Inner = Builder->CreateOr(A, Op1);
2335 Inner->takeName(Op0);
2336 return BinaryOperator::CreateOr(Inner, C1);
2339 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2340 // Since this OR statement hasn't been optimized further yet, we hope
2341 // that this transformation will allow the new ORs to be optimized.
2343 Value *X = nullptr, *Y = nullptr;
2344 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2345 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2346 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2347 Value *orTrue = Builder->CreateOr(A, C);
2348 Value *orFalse = Builder->CreateOr(B, D);
2349 return SelectInst::Create(X, orTrue, orFalse);
2353 return Changed ? &I : nullptr;
2356 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2357 /// can fold these early and efficiently by morphing an existing instruction.
2358 static Instruction *foldXorToXor(BinaryOperator &I) {
2359 assert(I.getOpcode() == Instruction::Xor);
2360 Value *Op0 = I.getOperand(0);
2361 Value *Op1 = I.getOperand(1);
2364 // There are 4 commuted variants for each of the basic patterns.
2366 // (A & B) ^ (A | B) -> A ^ B
2367 // (A & B) ^ (B | A) -> A ^ B
2368 // (A | B) ^ (A & B) -> A ^ B
2369 // (A | B) ^ (B & A) -> A ^ B
2370 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2371 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2372 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2373 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2379 // (A | ~B) ^ (~A | B) -> A ^ B
2380 // (~B | A) ^ (~A | B) -> A ^ B
2381 // (~A | B) ^ (A | ~B) -> A ^ B
2382 // (B | ~A) ^ (A | ~B) -> A ^ B
2383 if ((match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2384 match(Op1, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2385 (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2386 match(Op1, m_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
2392 // (A & ~B) ^ (~A & B) -> A ^ B
2393 // (~B & A) ^ (~A & B) -> A ^ B
2394 // (~A & B) ^ (A & ~B) -> A ^ B
2395 // (B & ~A) ^ (A & ~B) -> A ^ B
2396 if ((match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2397 match(Op1, m_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2398 (match(Op0, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2399 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))) {
2408 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2409 // here. We should standardize that construct where it is needed or choose some
2410 // other way to ensure that commutated variants of patterns are not missed.
2411 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2412 bool Changed = SimplifyAssociativeOrCommutative(I);
2413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2415 if (Value *V = SimplifyVectorOp(I))
2416 return replaceInstUsesWith(I, V);
2418 if (Value *V = SimplifyXorInst(Op0, Op1, DL, &TLI, &DT, &AC))
2419 return replaceInstUsesWith(I, V);
2421 if (Instruction *NewXor = foldXorToXor(I))
2424 // (A&B)^(A&C) -> A&(B^C) etc
2425 if (Value *V = SimplifyUsingDistributiveLaws(I))
2426 return replaceInstUsesWith(I, V);
2428 // See if we can simplify any instructions used by the instruction whose sole
2429 // purpose is to compute bits we don't care about.
2430 if (SimplifyDemandedInstructionBits(I))
2433 if (Value *V = SimplifyBSwap(I))
2434 return replaceInstUsesWith(I, V);
2436 // Is this a 'not' (~) fed by a binary operator?
2437 BinaryOperator *NotOp;
2438 if (match(&I, m_Not(m_BinOp(NotOp)))) {
2439 if (NotOp->getOpcode() == Instruction::And ||
2440 NotOp->getOpcode() == Instruction::Or) {
2441 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2442 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2443 if (dyn_castNotVal(NotOp->getOperand(1)))
2444 NotOp->swapOperands();
2445 if (Value *Op0NotVal = dyn_castNotVal(NotOp->getOperand(0))) {
2446 Value *NotY = Builder->CreateNot(
2447 NotOp->getOperand(1), NotOp->getOperand(1)->getName() + ".not");
2448 if (NotOp->getOpcode() == Instruction::And)
2449 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2450 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2453 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2454 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2455 if (IsFreeToInvert(NotOp->getOperand(0),
2456 NotOp->getOperand(0)->hasOneUse()) &&
2457 IsFreeToInvert(NotOp->getOperand(1),
2458 NotOp->getOperand(1)->hasOneUse())) {
2459 Value *NotX = Builder->CreateNot(NotOp->getOperand(0), "notlhs");
2460 Value *NotY = Builder->CreateNot(NotOp->getOperand(1), "notrhs");
2461 if (NotOp->getOpcode() == Instruction::And)
2462 return BinaryOperator::CreateOr(NotX, NotY);
2463 return BinaryOperator::CreateAnd(NotX, NotY);
2465 } else if (NotOp->getOpcode() == Instruction::AShr) {
2466 // ~(~X >>s Y) --> (X >>s Y)
2467 if (Value *Op0NotVal = dyn_castNotVal(NotOp->getOperand(0)))
2468 return BinaryOperator::CreateAShr(Op0NotVal, NotOp->getOperand(1));
2472 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2473 ICmpInst::Predicate Pred;
2474 if (match(Op0, m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))) &&
2475 match(Op1, m_AllOnes())) {
2476 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2477 return replaceInstUsesWith(I, Op0);
2480 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
2481 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2482 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2483 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2484 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2485 Instruction::CastOps Opcode = Op0C->getOpcode();
2486 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2487 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2488 Op0C->getDestTy()))) {
2489 CI->setPredicate(CI->getInversePredicate());
2490 return CastInst::Create(Opcode, CI, Op0C->getType());
2496 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2497 // ~(c-X) == X-c-1 == X+(-c-1)
2498 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
2499 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2500 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2501 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2505 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2506 if (Op0I->getOpcode() == Instruction::Add) {
2507 // ~(X-c) --> (-c-1)-X
2508 if (RHSC->isAllOnesValue()) {
2509 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2510 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2511 Op0I->getOperand(0));
2512 } else if (RHSC->getValue().isSignMask()) {
2513 // (X + C) ^ signmask -> (X + C + signmask)
2514 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
2515 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2518 } else if (Op0I->getOpcode() == Instruction::Or) {
2519 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2520 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2522 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
2523 // Anything in both C1 and C2 is known to be zero, remove it from
2525 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
2526 NewRHS = ConstantExpr::getAnd(NewRHS,
2527 ConstantExpr::getNot(CommonBits));
2529 I.setOperand(0, Op0I->getOperand(0));
2530 I.setOperand(1, NewRHS);
2533 } else if (Op0I->getOpcode() == Instruction::LShr) {
2534 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2538 if (Op0I->hasOneUse() &&
2539 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2540 E1->getOpcode() == Instruction::Xor &&
2541 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2542 // fold (C1 >> C2) ^ C3
2543 ConstantInt *C2 = Op0CI, *C3 = RHSC;
2544 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2545 FoldConst ^= C3->getValue();
2546 // Prepare the two operands.
2547 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2548 Opnd0->takeName(Op0I);
2549 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2550 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2552 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2559 if (isa<Constant>(Op1))
2560 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2565 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
2566 if (A == Op0) { // A^(A|B) == A^(B|A)
2567 cast<BinaryOperator>(Op1)->swapOperands();
2570 if (B == Op0) { // A^(B|A) == (B|A)^A
2571 I.swapOperands(); // Simplified below.
2572 std::swap(Op0, Op1);
2574 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
2575 if (A == Op0) { // A^(A&B) -> A^(B&A)
2576 cast<BinaryOperator>(Op1)->swapOperands();
2579 if (B == Op0) { // A^(B&A) -> (B&A)^A
2580 I.swapOperands(); // Simplified below.
2581 std::swap(Op0, Op1);
2588 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
2589 if (A == Op1) // (B|A)^B == (A|B)^B
2591 if (B == Op1) // (A|B)^B == A & ~B
2592 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2593 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
2594 if (A == Op1) // (A&B)^A -> (B&A)^A
2597 if (B == Op1 && // (B&A)^A == ~B & A
2598 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
2599 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2605 Value *A, *B, *C, *D;
2606 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2607 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2608 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
2610 return BinaryOperator::CreateXor(
2611 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2613 return BinaryOperator::CreateXor(
2614 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2616 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2617 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2618 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
2620 return BinaryOperator::CreateXor(
2621 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2623 return BinaryOperator::CreateXor(
2624 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2626 // (A & B) ^ (A ^ B) -> (A | B)
2627 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2628 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2629 return BinaryOperator::CreateOr(A, B);
2630 // (A ^ B) ^ (A & B) -> (A | B)
2631 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2632 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
2633 return BinaryOperator::CreateOr(A, B);
2636 // (A & ~B) ^ ~A -> ~(A & B)
2637 // (~B & A) ^ ~A -> ~(A & B)
2639 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2640 match(Op1, m_Not(m_Specific(A))))
2641 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2643 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2644 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2645 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2646 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2647 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2648 LHS->getOperand(1) == RHS->getOperand(0))
2649 LHS->swapOperands();
2650 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2651 LHS->getOperand(1) == RHS->getOperand(1)) {
2652 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2653 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2654 bool isSigned = LHS->isSigned() || RHS->isSigned();
2655 return replaceInstUsesWith(I,
2656 getNewICmpValue(isSigned, Code, Op0, Op1,
2661 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2664 return Changed ? &I : nullptr;