blob: d7d460b7c04c74304b4a10ae826bb70f1b5759c3 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000057 InstCombiner::BuilderTy &Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
Craig Topperbb4069e2017-07-07 23:16:26 +000061 return Builder.CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000067 InstCombiner::BuilderTy &Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Craig Topperbb4069e2017-07-07 23:16:26 +000075 return Builder.CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
Craig Topper95e41422017-07-06 16:24:23 +000083static Value *SimplifyBSwap(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +000084 InstCombiner::BuilderTy &Builder) {
Craig Topperc6948c22017-07-03 05:54:11 +000085 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86
Craig Topper22795de2017-07-06 16:24:21 +000087 Value *OldLHS = I.getOperand(0);
88 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000089
Craig Topper766ce6e2017-07-03 05:54:15 +000090 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000091 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000092 return nullptr;
93
Craig Topper766ce6e2017-07-03 05:54:15 +000094 Value *NewRHS;
95 const APInt *C;
96
Craig Topper22795de2017-07-06 16:24:21 +000097 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000098 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000099 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
100 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000102 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000103 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000104 if (!OldLHS->hasOneUse())
105 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000106 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
107 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000108 return nullptr;
109
Craig Topperbb4069e2017-07-07 23:16:26 +0000110 Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000111 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
112 I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000113 return Builder.CreateCall(F, BinOp);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000114}
115
Sanjay Patel18549272015-09-08 18:24:36 +0000116/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000117/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
118Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000119 ConstantInt *OpRHS,
120 ConstantInt *AndRHS,
121 BinaryOperator &TheAnd) {
122 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000123 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000124 if (!Op->isShift())
125 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
126
127 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000128 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000129 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000130 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000131 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
132 if (TogetherCI && !TogetherCI->isZero()){
133 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
134 // NOTE: This reduces the number of bits set in the & mask, which
135 // can expose opportunities for store narrowing.
136 Together = ConstantExpr::getXor(AndRHS, Together);
Craig Topperbb4069e2017-07-07 23:16:26 +0000137 Value *And = Builder.CreateAnd(X, Together);
Owen Andersonc237a842010-09-13 17:59:27 +0000138 And->takeName(Op);
139 return BinaryOperator::CreateOr(And, OpRHS);
140 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000141 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000142
Chris Lattner0a8191e2010-01-05 07:50:36 +0000143 break;
144 case Instruction::Add:
145 if (Op->hasOneUse()) {
146 // Adding a one to a single bit bit-field should be turned into an XOR
147 // of the bit. First thing to check is to see if this AND is with a
148 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000149 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000150
151 // If there is only one bit set.
152 if (AndRHSV.isPowerOf2()) {
153 // Ok, at this point, we know that we are masking the result of the
154 // ADD down to exactly one bit. If the constant we are adding has
155 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000156 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157
158 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000159 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000160 // If not, the only thing that can effect the output of the AND is
161 // the bit specified by AndRHSV. If that bit is set, the effect of
162 // the XOR is to toggle the bit. If it is clear, then the ADD has
163 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000164 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000165 TheAnd.setOperand(0, X);
166 return &TheAnd;
167 } else {
168 // Pull the XOR out of the AND.
Craig Topperbb4069e2017-07-07 23:16:26 +0000169 Value *NewAnd = Builder.CreateAnd(X, AndRHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000170 NewAnd->takeName(Op);
171 return BinaryOperator::CreateXor(NewAnd, AndRHS);
172 }
173 }
174 }
175 }
176 break;
177
178 case Instruction::Shl: {
179 // We know that the AND will not produce any of the bits shifted in, so if
180 // the anded constant includes them, clear them now!
181 //
182 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
183 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
184 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Craig Topperbb4069e2017-07-07 23:16:26 +0000185 ConstantInt *CI = Builder.getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000186
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000187 if (CI->getValue() == ShlMask)
188 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000189 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000190
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000191 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000192 TheAnd.setOperand(1, CI);
193 return &TheAnd;
194 }
195 break;
196 }
197 case Instruction::LShr: {
198 // We know that the AND will not produce any of the bits shifted in, so if
199 // the anded constant includes them, clear them now! This only applies to
200 // unsigned shifts, because a signed shr may bring in set bits!
201 //
202 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
203 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
204 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Craig Topperbb4069e2017-07-07 23:16:26 +0000205 ConstantInt *CI = Builder.getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000206
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000207 if (CI->getValue() == ShrMask)
208 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000209 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000210
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000211 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000212 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
213 return &TheAnd;
214 }
215 break;
216 }
217 case Instruction::AShr:
218 // Signed shr.
219 // See if this is shifting in some sign extension, then masking it out
220 // with an and.
221 if (Op->hasOneUse()) {
222 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
223 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
224 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Craig Topperbb4069e2017-07-07 23:16:26 +0000225 Constant *C = Builder.getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000226 if (C == AndRHS) { // Masking out bits shifted in.
227 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
228 // Make the argument unsigned.
229 Value *ShVal = Op->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +0000230 ShVal = Builder.CreateLShr(ShVal, OpRHS, Op->getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000231 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
232 }
233 }
234 break;
235 }
Craig Topperf40110f2014-04-25 05:29:35 +0000236 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000237}
238
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000239/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000240/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
241/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000242Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000243 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000244 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000245 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000246
Sanjay Patel85d79742016-08-31 19:49:56 +0000247 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000248 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000249 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000250
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000251 // V >= Min && V < Hi --> V < Hi
252 // V < Min || V >= Hi --> V >= Hi
253 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000254 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000255 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Craig Topperbb4069e2017-07-07 23:16:26 +0000256 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000257 }
258
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000259 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
260 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000261 Value *VMinusLo =
Craig Topperbb4069e2017-07-07 23:16:26 +0000262 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
Sanjay Patel85d79742016-08-31 19:49:56 +0000263 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Craig Topperbb4069e2017-07-07 23:16:26 +0000264 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000265}
266
Sanjay Patel77bf6222017-04-03 16:53:12 +0000267/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
268/// that can be simplified.
269/// One of A and B is considered the mask. The other is the value. This is
270/// described as the "AMask" or "BMask" part of the enum. If the enum contains
271/// only "Mask", then both A and B can be considered masks. If A is the mask,
272/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
273/// If both A and C are constants, this proof is also easy.
274/// For the following explanations, we assume that A is the mask.
275///
276/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
277/// bits of A are set in B.
278/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
279///
280/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
281/// bits of A are cleared in B.
282/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
283///
284/// "Mixed" declares that (A & B) == C and C might or might not contain any
285/// number of one bits and zero bits.
286/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
287///
288/// "Not" means that in above descriptions "==" should be replaced by "!=".
289/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
290///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000291/// If the mask A contains a single bit, then the following is equivalent:
292/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
293/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
294enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000295 AMask_AllOnes = 1,
296 AMask_NotAllOnes = 2,
297 BMask_AllOnes = 4,
298 BMask_NotAllOnes = 8,
299 Mask_AllZeros = 16,
300 Mask_NotAllZeros = 32,
301 AMask_Mixed = 64,
302 AMask_NotMixed = 128,
303 BMask_Mixed = 256,
304 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000305};
306
Sanjay Patel77bf6222017-04-03 16:53:12 +0000307/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
308/// satisfies.
309static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
310 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000311 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
312 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
313 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000314 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
315 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
316 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
317 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000318 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000319 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000320 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
321 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
322 if (IsAPow2)
323 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
324 : (AMask_AllOnes | AMask_Mixed));
325 if (IsBPow2)
326 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
327 : (BMask_AllOnes | BMask_Mixed));
328 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000329 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000330
Owen Anderson3fe002d2010-09-08 22:16:17 +0000331 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000332 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
333 : (AMask_NotAllOnes | AMask_NotMixed));
334 if (IsAPow2)
335 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
336 : (Mask_AllZeros | AMask_Mixed));
337 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
338 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000339 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000340
Craig Topperae48cb22012-12-20 07:15:54 +0000341 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000342 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
343 : (BMask_NotAllOnes | BMask_NotMixed));
344 if (IsBPow2)
345 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
346 : (Mask_AllZeros | BMask_Mixed));
347 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
348 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000349 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000350
351 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000352}
353
Tim Northoverc0756c42013-09-04 11:57:13 +0000354/// Convert an analysis of a masked ICmp into its equivalent if all boolean
355/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
356/// is adjacent to the corresponding normal flag (recording ==), this just
357/// involves swapping those bits over.
358static unsigned conjugateICmpMask(unsigned Mask) {
359 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000360 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
361 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000362 << 1;
363
Sanjay Patel77bf6222017-04-03 16:53:12 +0000364 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
365 AMask_NotMixed | BMask_NotMixed))
366 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000367
368 return NewMask;
369}
370
Sanjay Patel77bf6222017-04-03 16:53:12 +0000371/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
372/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
373/// RHS satisfy.
374static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
375 Value *&D, Value *&E, ICmpInst *LHS,
376 ICmpInst *RHS,
377 ICmpInst::Predicate &PredL,
378 ICmpInst::Predicate &PredR) {
379 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
380 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000381 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000382 if (LHS->getOperand(0)->getType()->isVectorTy())
383 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000384
385 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000386 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000387 // and L11 & L12 == L21 & L22. The same goes for RHS.
388 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000389 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000390 // above.
391 Value *L1 = LHS->getOperand(0);
392 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000393 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000394 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000395 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000396 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000397 } else {
398 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000399 if (!L1->getType()->isIntegerTy()) {
400 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000401 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000402 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
403 // Any icmp can be viewed as being trivially masked; if it allows us to
404 // remove one, it's worth it.
405 L11 = L1;
406 L12 = Constant::getAllOnesValue(L1->getType());
407 }
408
409 if (!L2->getType()->isIntegerTy()) {
410 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000411 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000412 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
413 L21 = L2;
414 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000415 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000416 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000417
418 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000419 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000420 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000421
422 Value *R1 = RHS->getOperand(0);
423 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000424 Value *R11, *R12;
425 bool Ok = false;
426 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000427 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000428 A = R11;
429 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000430 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 A = R12;
432 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000433 } else {
434 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000435 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000436 E = R2;
437 R1 = nullptr;
438 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000439 } else if (R1->getType()->isIntegerTy()) {
440 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
441 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000442 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000443 R11 = R1;
444 R12 = Constant::getAllOnesValue(R1->getType());
445 }
446
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000447 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000448 A = R11;
449 D = R12;
450 E = R2;
451 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000452 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000453 A = R12;
454 D = R11;
455 E = R2;
456 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000457 }
458 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000459
460 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000461 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000462 return 0;
463
Chad Rosier58919cc2016-05-09 21:37:43 +0000464 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000465 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000466 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
467 R11 = R2;
468 R12 = Constant::getAllOnesValue(R2->getType());
469 }
470
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000471 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000472 A = R11;
473 D = R12;
474 E = R1;
475 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000476 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000477 A = R12;
478 D = R11;
479 E = R1;
480 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000481 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000482 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000483 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000484 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000485 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000486 return 0;
487
488 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000489 B = L12;
490 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000491 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000492 B = L11;
493 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000494 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000495 B = L22;
496 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000497 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000498 B = L21;
499 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000500 }
501
Sanjay Patel77bf6222017-04-03 16:53:12 +0000502 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
503 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000504 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000505}
Sanjay Patel18549272015-09-08 18:24:36 +0000506
507/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
508/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000509static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000510 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000511 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000512 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
513 unsigned Mask =
514 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
515 if (Mask == 0)
516 return nullptr;
517
518 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
519 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000520
Tim Northoverc0756c42013-09-04 11:57:13 +0000521 // In full generality:
522 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
523 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
524 //
525 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
526 // equivalent to (icmp (A & X) !Op Y).
527 //
528 // Therefore, we can pretend for the rest of this function that we're dealing
529 // with the conjunction, provided we flip the sense of any comparisons (both
530 // input and output).
531
532 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000533 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000534 if (!IsAnd) {
535 // Convert the masking analysis into its equivalent with negated
536 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000537 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000538 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000539
Sanjay Patel77bf6222017-04-03 16:53:12 +0000540 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000541 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000542 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000543 Value *NewOr = Builder.CreateOr(B, D);
544 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000545 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000546 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000547 // with B and D, having a single bit set.
548 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000549 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000550 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000551 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000552 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000553 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000554 Value *NewOr = Builder.CreateOr(B, D);
555 Value *NewAnd = Builder.CreateAnd(A, NewOr);
556 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000557 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000558 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000559 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000561 Value *NewAnd1 = Builder.CreateAnd(B, D);
562 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
563 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000565
566 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000567 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000568 // easy cases for now" decision.
569 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000570 if (!BCst)
571 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000572 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000573 if (!DCst)
574 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000575
Sanjay Patel77bf6222017-04-03 16:53:12 +0000576 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000577 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
578 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
579 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
580 // Only valid if one of the masks is a superset of the other (check "B&D" is
581 // the same as either B or D).
582 APInt NewMask = BCst->getValue() & DCst->getValue();
583
584 if (NewMask == BCst->getValue())
585 return LHS;
586 else if (NewMask == DCst->getValue())
587 return RHS;
588 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000589
590 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000591 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
592 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
593 // Only valid if one of the masks is a superset of the other (check "B|D" is
594 // the same as either B or D).
595 APInt NewMask = BCst->getValue() | DCst->getValue();
596
597 if (NewMask == BCst->getValue())
598 return LHS;
599 else if (NewMask == DCst->getValue())
600 return RHS;
601 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000602
603 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000604 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000605 // We already know that B & C == C && D & E == E.
606 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
607 // C and E, which are shared by both the mask B and the mask D, don't
608 // contradict, then we can transform to
609 // -> (icmp eq (A & (B|D)), (C|E))
610 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000611 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000612 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000613 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000614 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000615 if (!CCst)
616 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000617 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000618 if (!ECst)
619 return nullptr;
620 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000621 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000622 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000623 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000624
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000625 // If there is a conflict, we should actually return a false for the
626 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000627 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000628 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000629 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000630
Craig Topperbb4069e2017-07-07 23:16:26 +0000631 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000632 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000633 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
634 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000635 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000636
Craig Topperf40110f2014-04-25 05:29:35 +0000637 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000638}
639
Erik Ecksteind1817522014-12-03 10:39:15 +0000640/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
641/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
642/// If \p Inverted is true then the check is for the inverted range, e.g.
643/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
644Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
645 bool Inverted) {
646 // Check the lower range comparison, e.g. x >= 0
647 // InstCombine already ensured that if there is a constant it's on the RHS.
648 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
649 if (!RangeStart)
650 return nullptr;
651
652 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
653 Cmp0->getPredicate());
654
655 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
656 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
657 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
658 return nullptr;
659
660 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
661 Cmp1->getPredicate());
662
663 Value *Input = Cmp0->getOperand(0);
664 Value *RangeEnd;
665 if (Cmp1->getOperand(0) == Input) {
666 // For the upper range compare we have: icmp x, n
667 RangeEnd = Cmp1->getOperand(1);
668 } else if (Cmp1->getOperand(1) == Input) {
669 // For the upper range compare we have: icmp n, x
670 RangeEnd = Cmp1->getOperand(0);
671 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
672 } else {
673 return nullptr;
674 }
675
676 // Check the upper range comparison, e.g. x < n
677 ICmpInst::Predicate NewPred;
678 switch (Pred1) {
679 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
680 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
681 default: return nullptr;
682 }
683
684 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000685 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
686 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000687 return nullptr;
688
689 if (Inverted)
690 NewPred = ICmpInst::getInversePredicate(NewPred);
691
Craig Topperbb4069e2017-07-07 23:16:26 +0000692 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000693}
694
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000695static Value *
696foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
697 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000698 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000699 Value *X = LHS->getOperand(0);
700 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000701 return nullptr;
702
Sanjay Patelef9f5862017-04-15 17:55:06 +0000703 const APInt *C1, *C2;
704 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
705 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000706 return nullptr;
707
708 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
709 ICmpInst::Predicate Pred = LHS->getPredicate();
710 if (Pred != RHS->getPredicate())
711 return nullptr;
712 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
713 return nullptr;
714 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
715 return nullptr;
716
717 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000718 if (C1->ugt(*C2))
719 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000720
Sanjay Patelef9f5862017-04-15 17:55:06 +0000721 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000722 if (Xor.isPowerOf2()) {
723 // If LHSC and RHSC differ by only one bit, then set that bit in X and
724 // compare against the larger constant:
725 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
726 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
727 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
728 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000729 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
730 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000731 }
732
733 // Special case: get the ordering right when the values wrap around zero.
734 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000735 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000736 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000737
Sanjay Patelef9f5862017-04-15 17:55:06 +0000738 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000739 // (X == 13 || X == 14) --> X - 13 <=u 1
740 // (X != 13 && X != 14) --> X - 13 >u 1
741 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000742 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000743 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000744 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000745 }
746
747 return nullptr;
748}
749
Craig Topperda6ea0d2017-06-16 05:10:37 +0000750// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
751// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
752Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
753 bool JoinedByAnd,
754 Instruction &CxtI) {
755 ICmpInst::Predicate Pred = LHS->getPredicate();
756 if (Pred != RHS->getPredicate())
757 return nullptr;
758 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
759 return nullptr;
760 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
761 return nullptr;
762
763 // TODO support vector splats
764 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
765 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
766 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
767 return nullptr;
768
769 Value *A, *B, *C, *D;
770 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
771 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
772 if (A == D || B == D)
773 std::swap(C, D);
774 if (B == C)
775 std::swap(A, B);
776
777 if (A == C &&
778 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
779 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000780 Value *Mask = Builder.CreateOr(B, D);
781 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000782 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000783 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000784 }
785 }
786
787 return nullptr;
788}
789
Sanjay Patel18549272015-09-08 18:24:36 +0000790/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000791Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
792 Instruction &CxtI) {
793 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
794 // if K1 and K2 are a one-bit mask.
795 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
796 return V;
797
Sanjay Patel519a87a2017-04-05 17:38:34 +0000798 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000799
800 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000801 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000802 if (LHS->getOperand(0) == RHS->getOperand(1) &&
803 LHS->getOperand(1) == RHS->getOperand(0))
804 LHS->swapOperands();
805 if (LHS->getOperand(0) == RHS->getOperand(0) &&
806 LHS->getOperand(1) == RHS->getOperand(1)) {
807 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
808 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
809 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000810 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000811 }
812 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000813
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000814 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000815 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000816 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000817
Erik Ecksteind1817522014-12-03 10:39:15 +0000818 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
819 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
820 return V;
821
822 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
823 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
824 return V;
825
Sanjay Patelef9f5862017-04-15 17:55:06 +0000826 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
827 return V;
828
Chris Lattner0a8191e2010-01-05 07:50:36 +0000829 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000830 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000831 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
832 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
833 if (!LHSC || !RHSC)
834 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000835
Sanjay Patel519a87a2017-04-05 17:38:34 +0000836 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000837 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000838 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000839 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000840 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
841 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000842 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
843 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000844 }
845 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000846
Benjamin Kramer101720f2011-04-28 20:09:57 +0000847 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000848 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000849 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
851 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000852 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000853 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000854
855 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000856 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000857 if (match(RHS0, m_Trunc(m_Value(V))) &&
858 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000859 SmallC = RHSC;
860 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000861 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
862 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000863 SmallC = LHSC;
864 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000865 }
866
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 if (SmallC && BigC) {
868 unsigned BigBitSize = BigC->getType()->getBitWidth();
869 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000870
871 // Check that the low bits are zero.
872 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000873 if ((Low & AndC->getValue()).isNullValue() &&
874 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000875 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +0000876 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
877 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +0000878 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000879 }
880 }
881 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000882
Chris Lattner0a8191e2010-01-05 07:50:36 +0000883 // From here on, we only handle:
884 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000885 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000886 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000887
Sanjay Patel519a87a2017-04-05 17:38:34 +0000888 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
889 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
890 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
891 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
892 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000893 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000894
Chris Lattner0a8191e2010-01-05 07:50:36 +0000895 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000896 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000897 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000898
Chris Lattner0a8191e2010-01-05 07:50:36 +0000899 // Ensure that the larger constant is on the RHS.
900 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000901 if (CmpInst::isSigned(PredL) ||
902 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000903 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000904 else
905 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000906
Chris Lattner0a8191e2010-01-05 07:50:36 +0000907 if (ShouldSwap) {
908 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000909 std::swap(LHSC, RHSC);
910 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 }
912
Dan Gohman4a618822010-02-10 16:03:48 +0000913 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000914 // comparing a value against two constants and and'ing the result
915 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000916 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
917 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000918 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000919 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000920
Sanjay Patel519a87a2017-04-05 17:38:34 +0000921 switch (PredL) {
922 default:
923 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000925 switch (PredR) {
926 default:
927 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000928 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000929 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000930 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000931 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000932 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000933 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000934 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000936 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000937 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000938 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000939 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000940 // Potential folds for this case should already be handled.
941 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000942 }
943 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000944 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000945 switch (PredR) {
946 default:
947 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000948 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000949 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000950 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000951 break; // (X u> 13 & X != 15) -> no change
952 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000953 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
954 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000955 }
956 break;
957 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000958 switch (PredR) {
959 default:
960 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000961 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000962 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000963 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000964 break; // (X s> 13 & X != 15) -> no change
965 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000966 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000967 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000968 }
969 break;
970 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000971
Craig Topperf40110f2014-04-25 05:29:35 +0000972 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000973}
974
Sanjay Patel18549272015-09-08 18:24:36 +0000975/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
976/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000977Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000978 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
979 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
980 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
981
982 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
983 // Swap RHS operands to match LHS.
984 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
985 std::swap(Op1LHS, Op1RHS);
986 }
987
988 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
989 // Suppose the relation between x and y is R, where R is one of
990 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
991 // testing the desired relations.
992 //
993 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
994 // bool(R & CC0) && bool(R & CC1)
995 // = bool((R & CC0) & (R & CC1))
996 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
997 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
998 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
999 Builder);
1000
Chris Lattner0a8191e2010-01-05 07:50:36 +00001001 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1002 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001003 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001004 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001005
Chris Lattner0a8191e2010-01-05 07:50:36 +00001006 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1007 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1008 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1009 // If either of the constants are nans, then the whole thing returns
1010 // false.
1011 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +00001012 return Builder.getFalse();
1013 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001015
Chris Lattner0a8191e2010-01-05 07:50:36 +00001016 // Handle vector zeros. This occurs because the canonical form of
1017 // "fcmp ord x,x" is "fcmp ord x, 0".
1018 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1019 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +00001020 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001021 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001023
Craig Topperf40110f2014-04-25 05:29:35 +00001024 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001025}
1026
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001027/// Match De Morgan's Laws:
1028/// (~A & ~B) == (~(A | B))
1029/// (~A | ~B) == (~(A & B))
1030static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001031 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001032 auto Opcode = I.getOpcode();
1033 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1034 "Trying to match De Morgan's Laws with something other than and/or");
1035
Sanjay Patel7caaa792017-05-09 20:05:05 +00001036 // Flip the logic operation.
1037 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1038
1039 Value *A, *B;
1040 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1041 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1042 !IsFreeToInvert(A, A->hasOneUse()) &&
1043 !IsFreeToInvert(B, B->hasOneUse())) {
1044 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1045 return BinaryOperator::CreateNot(AndOr);
1046 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001047
1048 return nullptr;
1049}
1050
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001051bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1052 Value *CastSrc = CI->getOperand(0);
1053
1054 // Noop casts and casts of constants should be eliminated trivially.
1055 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1056 return false;
1057
1058 // If this cast is paired with another cast that can be eliminated, we prefer
1059 // to have it eliminated.
1060 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1061 if (isEliminableCastPair(PrecedingCI, CI))
1062 return false;
1063
1064 // If this is a vector sext from a compare, then we don't want to break the
1065 // idiom where each element of the extended vector is either zero or all ones.
1066 if (CI->getOpcode() == Instruction::SExt &&
1067 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1068 return false;
1069
1070 return true;
1071}
1072
Sanjay Patel60312bc42016-09-12 00:16:23 +00001073/// Fold {and,or,xor} (cast X), C.
1074static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +00001075 InstCombiner::BuilderTy &Builder) {
Sanjay Patel60312bc42016-09-12 00:16:23 +00001076 Constant *C;
1077 if (!match(Logic.getOperand(1), m_Constant(C)))
1078 return nullptr;
1079
1080 auto LogicOpc = Logic.getOpcode();
1081 Type *DestTy = Logic.getType();
1082 Type *SrcTy = Cast->getSrcTy();
1083
Craig Topperae9b87d2017-08-02 20:25:56 +00001084 // Move the logic operation ahead of a zext or sext if the constant is
1085 // unchanged in the smaller source type. Performing the logic in a smaller
1086 // type may provide more information to later folds, and the smaller logic
1087 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001088 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001089 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1090 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1091 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1092 if (ZextTruncC == C) {
1093 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001094 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001095 return new ZExtInst(NewOp, DestTy);
1096 }
1097 }
1098
Craig Topperae9b87d2017-08-02 20:25:56 +00001099 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1100 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1101 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1102 if (SextTruncC == C) {
1103 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1104 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1105 return new SExtInst(NewOp, DestTy);
1106 }
1107 }
1108
Sanjay Patel60312bc42016-09-12 00:16:23 +00001109 return nullptr;
1110}
1111
1112/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001113Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001114 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001115 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001116
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001118 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001119 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001120 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001121
Sanjay Patel9bba7502016-03-03 19:19:04 +00001122 // This must be a cast from an integer or integer vector source type to allow
1123 // transformation of the logic operation to the source type.
1124 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001125 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001126 if (!SrcTy->isIntOrIntVectorTy())
1127 return nullptr;
1128
Sanjay Patel60312bc42016-09-12 00:16:23 +00001129 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1130 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001131
Sanjay Patel9bba7502016-03-03 19:19:04 +00001132 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1133 if (!Cast1)
1134 return nullptr;
1135
1136 // Both operands of the logic operation are casts. The casts must be of the
1137 // same type for reduction.
1138 auto CastOpcode = Cast0->getOpcode();
1139 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001140 return nullptr;
1141
1142 Value *Cast0Src = Cast0->getOperand(0);
1143 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001144
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001145 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001146 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001147 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001148 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001149 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001150 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001151
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001152 // For now, only 'and'/'or' have optimizations after this.
1153 if (LogicOpc == Instruction::Xor)
1154 return nullptr;
1155
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001156 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001157 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001158 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1159 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1160 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001161 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001162 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001163 if (Res)
1164 return CastInst::Create(CastOpcode, Res, DestTy);
1165 return nullptr;
1166 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001167
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001168 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001169 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001170 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1171 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1172 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001173 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1174 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001175 if (Res)
1176 return CastInst::Create(CastOpcode, Res, DestTy);
1177 return nullptr;
1178 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001179
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001180 return nullptr;
1181}
1182
Sanjay Patele0c26e02017-04-23 22:00:02 +00001183static Instruction *foldAndToXor(BinaryOperator &I,
1184 InstCombiner::BuilderTy &Builder) {
1185 assert(I.getOpcode() == Instruction::And);
1186 Value *Op0 = I.getOperand(0);
1187 Value *Op1 = I.getOperand(1);
1188 Value *A, *B;
1189
1190 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1191 // (A | B) & ~(A & B) --> A ^ B
1192 // (A | B) & ~(B & A) --> A ^ B
1193 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1194 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1195 return BinaryOperator::CreateXor(A, B);
1196
1197 // (A | ~B) & (~A | B) --> ~(A ^ B)
1198 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1199 // (~B | A) & (~A | B) --> ~(A ^ B)
1200 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001201 if (Op0->hasOneUse() || Op1->hasOneUse())
1202 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1203 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1204 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001205
1206 return nullptr;
1207}
1208
1209static Instruction *foldOrToXor(BinaryOperator &I,
1210 InstCombiner::BuilderTy &Builder) {
1211 assert(I.getOpcode() == Instruction::Or);
1212 Value *Op0 = I.getOperand(0);
1213 Value *Op1 = I.getOperand(1);
1214 Value *A, *B;
1215
1216 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1217 // (A & B) | ~(A | B) --> ~(A ^ B)
1218 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001219 if (Op0->hasOneUse() || Op1->hasOneUse())
1220 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1221 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1222 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001223
1224 // (A & ~B) | (~A & B) --> A ^ B
1225 // (A & ~B) | (B & ~A) --> A ^ B
1226 // (~B & A) | (~A & B) --> A ^ B
1227 // (~B & A) | (B & ~A) --> A ^ B
1228 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1229 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1230 return BinaryOperator::CreateXor(A, B);
1231
1232 return nullptr;
1233}
1234
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001235// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1236// here. We should standardize that construct where it is needed or choose some
1237// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001238Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001239 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001240 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1241
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001242 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001243 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001244
Craig Toppera4205622017-06-09 03:21:29 +00001245 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001246 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001247
Craig Topper9d4171a2012-12-20 07:09:41 +00001248 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001249 // purpose is to compute bits we don't care about.
1250 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001251 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001252
Sanjay Patele0c26e02017-04-23 22:00:02 +00001253 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001254 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001255 return Xor;
1256
1257 // (A|B)&(A|C) -> A|(B&C) etc
1258 if (Value *V = SimplifyUsingDistributiveLaws(I))
1259 return replaceInstUsesWith(I, V);
1260
Craig Topper95e41422017-07-06 16:24:23 +00001261 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001262 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001263
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001264 const APInt *C;
1265 if (match(Op1, m_APInt(C))) {
1266 Value *X, *Y;
1267 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1268 C->isOneValue()) {
1269 // (1 << X) & 1 --> zext(X == 0)
1270 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001271 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1272 return new ZExtInst(IsZero, I.getType());
1273 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001274
Craig Toppera1693a22017-08-06 23:11:49 +00001275 const APInt *XorC;
1276 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1277 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1278 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1279 Value *And = Builder.CreateAnd(X, Op1);
1280 And->takeName(Op0);
1281 return BinaryOperator::CreateXor(And, NewC);
1282 }
1283
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001284 // If the mask is only needed on one incoming arm, push the 'and' op up.
1285 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1286 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1287 APInt NotAndMask(~(*C));
1288 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1289 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1290 // Not masking anything out for the LHS, move mask to RHS.
1291 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1292 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1293 return BinaryOperator::Create(BinOp, X, NewRHS);
1294 }
1295 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1296 // Not masking anything out for the RHS, move mask to LHS.
1297 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1298 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1299 return BinaryOperator::Create(BinOp, NewLHS, Y);
1300 }
1301 }
Craig Toppera1693a22017-08-06 23:11:49 +00001302
Sanjay Patel3437ee22017-07-15 17:26:01 +00001303 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001304
Chris Lattner0a8191e2010-01-05 07:50:36 +00001305 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1306 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001307
1308 // Optimize a variety of ((val OP C1) & C2) combinations...
1309 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001310 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1311 // of X and OP behaves well when given trunc(C1) and X.
1312 switch (Op0I->getOpcode()) {
1313 default:
1314 break;
1315 case Instruction::Xor:
1316 case Instruction::Or:
1317 case Instruction::Mul:
1318 case Instruction::Add:
1319 case Instruction::Sub:
1320 Value *X;
1321 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001322 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001323 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1324 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1325 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001326 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001327 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001328 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001329 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001330 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001331 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001332 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001333 return new ZExtInst(And, I.getType());
1334 }
1335 }
1336 }
1337
Chris Lattner0a8191e2010-01-05 07:50:36 +00001338 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1339 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1340 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001341 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001342
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001343 // If this is an integer truncation, and if the source is an 'and' with
1344 // immediate, transform it. This frequently occurs for bitfield accesses.
1345 {
Craig Topperf40110f2014-04-25 05:29:35 +00001346 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001347 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1348 // Change: and (trunc (and X, YC) to T), C2
1349 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001350 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001351 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001352 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001353 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1354 C3 = ConstantExpr::getAnd(C3, AndRHS);
1355 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001356 }
1357 }
Craig Topper86173602017-04-04 20:26:25 +00001358 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001359
Craig Topper86173602017-04-04 20:26:25 +00001360 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001361 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1362 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001363
Craig Topperbb4069e2017-07-07 23:16:26 +00001364 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001365 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001366
Chris Lattner0a8191e2010-01-05 07:50:36 +00001367 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001368 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001369 // A&(A^B) => A & ~B
1370 {
1371 Value *tmpOp0 = Op0;
1372 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001373 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001374 if (A == Op1 || B == Op1 ) {
1375 tmpOp1 = Op0;
1376 tmpOp0 = Op1;
1377 // Simplify below
1378 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001379 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001380
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001381 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001382 if (B == tmpOp0) {
1383 std::swap(A, B);
1384 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001385 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001386 // A is originally -1 (or a vector of -1 and undefs), then we enter
1387 // an endless loop. By checking that A is non-constant we ensure that
1388 // we will never get to the loop.
1389 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00001390 return BinaryOperator::CreateAnd(A, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001391 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 }
1393
David Majnemer42af3602014-07-30 21:26:37 +00001394 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1395 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1396 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001397 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001398 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001399
1400 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1401 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1402 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001403 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001404 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001405
1406 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001407 // (A | B) & (B ^ (~A)) -> (A & B)
1408 // (B | A) & ((~A) ^ B) -> (A & B)
1409 // (B | A) & (B ^ (~A)) -> (A & B)
1410 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1411 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001412 return BinaryOperator::CreateAnd(A, B);
1413
1414 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001415 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001416 // (B ^ (~A)) & (A | B) -> (A & B)
1417 // (B ^ (~A)) & (B | A) -> (A & B)
1418 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001419 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001420 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001421 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001422
David Majnemer5e96f1b2014-08-30 06:18:20 +00001423 {
1424 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1425 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1426 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001427 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001428 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001429
David Majnemer5e96f1b2014-08-30 06:18:20 +00001430 // TODO: Make this recursive; it's a little tricky because an arbitrary
1431 // number of 'and' instructions might have to be created.
1432 Value *X, *Y;
1433 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1434 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001435 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001436 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001437 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001438 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001439 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001440 }
1441 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1442 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001443 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001444 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001445 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001446 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001447 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001448 }
1449 }
1450
Chris Lattner4e8137d2010-02-11 06:26:33 +00001451 // If and'ing two fcmp, try combine them into one.
1452 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1453 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001454 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001455 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001456
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001457 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1458 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001459
Craig Topper760ff6e2017-08-04 16:07:20 +00001460 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1461 Value *A;
1462 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1463 A->getType()->isIntOrIntVectorTy(1))
1464 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1465 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1466 A->getType()->isIntOrIntVectorTy(1))
1467 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001468
Craig Topperf40110f2014-04-25 05:29:35 +00001469 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001470}
1471
Chad Rosiera00df492016-05-25 16:22:14 +00001472/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1473/// insert the new intrinsic and return it.
1474Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1476
1477 // Look through zero extends.
1478 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1479 Op0 = Ext->getOperand(0);
1480
1481 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1482 Op1 = Ext->getOperand(0);
1483
1484 // (A | B) | C and A | (B | C) -> bswap if possible.
1485 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1486 match(Op1, m_Or(m_Value(), m_Value()));
1487
1488 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1489 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1490 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1491
1492 // (A & B) | (C & D) -> bswap if possible.
1493 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1494 match(Op1, m_And(m_Value(), m_Value()));
1495
1496 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1497 return nullptr;
1498
James Molloyf01488e2016-01-15 09:20:19 +00001499 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001500 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001501 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001502 Instruction *LastInst = Insts.pop_back_val();
1503 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001504
James Molloyf01488e2016-01-15 09:20:19 +00001505 for (auto *Inst : Insts)
1506 Worklist.Add(Inst);
1507 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001508}
1509
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001510/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1511static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1512 unsigned NumElts = C1->getType()->getVectorNumElements();
1513 for (unsigned i = 0; i != NumElts; ++i) {
1514 Constant *EltC1 = C1->getAggregateElement(i);
1515 Constant *EltC2 = C2->getAggregateElement(i);
1516 if (!EltC1 || !EltC2)
1517 return false;
1518
1519 // One element must be all ones, and the other must be all zeros.
1520 // FIXME: Allow undef elements.
1521 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1522 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1523 return false;
1524 }
1525 return true;
1526}
1527
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001528/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1529/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1530/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001531static Value *getSelectCondition(Value *A, Value *B,
1532 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001533 // If these are scalars or vectors of i1, A can be used directly.
1534 Type *Ty = A->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001535 if (match(A, m_Not(m_Specific(B))) && Ty->isIntOrIntVectorTy(1))
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001536 return A;
1537
1538 // If A and B are sign-extended, look through the sexts to find the booleans.
1539 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001540 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001541 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001542 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001543 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1544 NotB = peekThroughBitcast(NotB, true);
1545 if (match(NotB, m_SExt(m_Specific(Cond))))
1546 return Cond;
1547 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001548
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001549 // All scalar (and most vector) possibilities should be handled now.
1550 // Try more matches that only apply to non-splat constant vectors.
1551 if (!Ty->isVectorTy())
1552 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001553
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001554 // If both operands are constants, see if the constants are inverse bitmasks.
1555 Constant *AC, *BC;
1556 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1557 areInverseVectorBitmasks(AC, BC))
1558 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1559
1560 // If both operands are xor'd with constants using the same sexted boolean
1561 // operand, see if the constants are inverse bitmasks.
1562 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1563 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001564 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001565 areInverseVectorBitmasks(AC, BC)) {
1566 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1567 return Builder.CreateXor(Cond, AC);
1568 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001569 return nullptr;
1570}
1571
1572/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1573/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001574static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001575 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001576 // The potential condition of the select may be bitcasted. In that case, look
1577 // through its bitcast and the corresponding bitcast of the 'not' condition.
1578 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001579 A = peekThroughBitcast(A, true);
1580 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001581
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001582 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001583 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001584 // The bitcasts will either all exist or all not exist. The builder will
1585 // not create unnecessary casts if the types already match.
1586 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1587 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1588 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1589 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001590 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001591
Craig Topperf40110f2014-04-25 05:29:35 +00001592 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001593}
1594
Sanjay Patel18549272015-09-08 18:24:36 +00001595/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001596Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001597 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001598 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1599 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001600 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1601 return V;
1602
1603 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1604
Sanjay Patel519a87a2017-04-05 17:38:34 +00001605 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1606 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001607
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001608 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1609 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1610 // The original condition actually refers to the following two ranges:
1611 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1612 // We can fold these two ranges if:
1613 // 1) C1 and C2 is unsigned greater than C3.
1614 // 2) The two ranges are separated.
1615 // 3) C1 ^ C2 is one-bit mask.
1616 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1617 // This implies all values in the two ranges differ by exactly one bit.
1618
Sanjay Patel519a87a2017-04-05 17:38:34 +00001619 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1620 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1621 LHSC->getType() == RHSC->getType() &&
1622 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001623
1624 Value *LAdd = LHS->getOperand(0);
1625 Value *RAdd = RHS->getOperand(0);
1626
1627 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001628 ConstantInt *LAddC, *RAddC;
1629 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1630 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1631 LAddC->getValue().ugt(LHSC->getValue()) &&
1632 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001633
Sanjay Patel519a87a2017-04-05 17:38:34 +00001634 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1635 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1636 ConstantInt *MaxAddC = nullptr;
1637 if (LAddC->getValue().ult(RAddC->getValue()))
1638 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001639 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001640 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001641
Sanjay Patel519a87a2017-04-05 17:38:34 +00001642 APInt RRangeLow = -RAddC->getValue();
1643 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1644 APInt LRangeLow = -LAddC->getValue();
1645 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001646 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1647 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1648 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1649 : RRangeLow - LRangeLow;
1650
1651 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001652 RangeDiff.ugt(LHSC->getValue())) {
1653 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001654
Craig Topperbb4069e2017-07-07 23:16:26 +00001655 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1656 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1657 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001658 }
1659 }
1660 }
1661 }
1662
Chris Lattner0a8191e2010-01-05 07:50:36 +00001663 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001664 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1666 LHS->getOperand(1) == RHS->getOperand(0))
1667 LHS->swapOperands();
1668 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1669 LHS->getOperand(1) == RHS->getOperand(1)) {
1670 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1671 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1672 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001673 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001674 }
1675 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001676
1677 // handle (roughly):
1678 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001679 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001680 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001681
Sanjay Patele4159d22017-04-10 19:38:36 +00001682 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001683 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1684 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1685 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001686 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001687 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001688 B = LHS0;
1689 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1690 A = RHS0;
1691 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001692 A = RHS->getOperand(1);
1693 }
1694 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1695 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001696 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001697 B = RHS0;
1698 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1699 A = LHS0;
1700 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001701 A = LHS->getOperand(1);
1702 }
1703 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00001704 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00001705 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00001706 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00001707 }
1708
Erik Ecksteind1817522014-12-03 10:39:15 +00001709 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1710 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1711 return V;
1712
1713 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1714 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1715 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001716
Sanjay Patelef9f5862017-04-15 17:55:06 +00001717 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1718 return V;
1719
David Majnemerc2a990b2013-07-05 00:31:17 +00001720 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001721 if (!LHSC || !RHSC)
1722 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001723
Sanjay Patel519a87a2017-04-05 17:38:34 +00001724 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001725 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001726 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001727 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1728 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001729 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001730 }
1731
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001732 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001733 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001734 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1735 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001736 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001737 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001738 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001739 }
1740
Chris Lattner0a8191e2010-01-05 07:50:36 +00001741 // From here on, we only handle:
1742 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001743 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001744 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001745
Sanjay Patel519a87a2017-04-05 17:38:34 +00001746 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1747 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1748 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1749 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1750 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001751 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001752
Chris Lattner0a8191e2010-01-05 07:50:36 +00001753 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001754 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001755 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001756
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757 // Ensure that the larger constant is on the RHS.
1758 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001759 if (CmpInst::isSigned(PredL) ||
1760 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001761 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001762 else
1763 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001764
Chris Lattner0a8191e2010-01-05 07:50:36 +00001765 if (ShouldSwap) {
1766 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001767 std::swap(LHSC, RHSC);
1768 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001769 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001770
Dan Gohman4a618822010-02-10 16:03:48 +00001771 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001772 // comparing a value against two constants and or'ing the result
1773 // together. Because of the above check, we know that we only have
1774 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1775 // icmp folding check above), that the two constants are not
1776 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001777 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001778
Sanjay Patel519a87a2017-04-05 17:38:34 +00001779 switch (PredL) {
1780 default:
1781 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001783 switch (PredR) {
1784 default:
1785 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001786 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001787 // Potential folds for this case should already be handled.
1788 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001789 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1790 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001791 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 }
1793 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001795 switch (PredR) {
1796 default:
1797 llvm_unreachable("Unknown integer condition code!");
1798 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001800 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001801 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001802 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1803 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 }
1805 break;
1806 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001807 switch (PredR) {
1808 default:
1809 llvm_unreachable("Unknown integer condition code!");
1810 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001812 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001813 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001814 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001815 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816 }
1817 break;
1818 }
Craig Topperf40110f2014-04-25 05:29:35 +00001819 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001820}
1821
Sanjay Patel18549272015-09-08 18:24:36 +00001822/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1823/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001824Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001825 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1826 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1827 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1828
1829 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1830 // Swap RHS operands to match LHS.
1831 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1832 std::swap(Op1LHS, Op1RHS);
1833 }
1834
1835 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1836 // This is a similar transformation to the one in FoldAndOfFCmps.
1837 //
1838 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1839 // bool(R & CC0) || bool(R & CC1)
1840 // = bool((R & CC0) | (R & CC1))
1841 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1842 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1843 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1844 Builder);
1845
Chris Lattner0a8191e2010-01-05 07:50:36 +00001846 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001847 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001848 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1849 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1850 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1851 // If either of the constants are nans, then the whole thing returns
1852 // true.
1853 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +00001854 return Builder.getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001855
Chris Lattner0a8191e2010-01-05 07:50:36 +00001856 // Otherwise, no need to compare the two constants, compare the
1857 // rest.
Craig Topperbb4069e2017-07-07 23:16:26 +00001858 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001859 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001860
Chris Lattner0a8191e2010-01-05 07:50:36 +00001861 // Handle vector zeros. This occurs because the canonical form of
1862 // "fcmp uno x,x" is "fcmp uno x, 0".
1863 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1864 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +00001865 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001866
Craig Topperf40110f2014-04-25 05:29:35 +00001867 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001868 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001869
Craig Topperf40110f2014-04-25 05:29:35 +00001870 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001871}
1872
Sanjay Patel18549272015-09-08 18:24:36 +00001873/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001874///
1875/// ((A | B) & C1) | (B & C2)
1876///
1877/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001878///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001879/// (A & C1) | B
1880///
1881/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001882static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1883 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001884 InstCombiner::BuilderTy &Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001886 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001887
Craig Topperf40110f2014-04-25 05:29:35 +00001888 Value *V1 = nullptr;
1889 ConstantInt *CI2 = nullptr;
1890 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001891
1892 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001893 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001894
1895 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001896 Value *NewOp = Builder.CreateAnd((V1 == A) ? B : A, CI1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 return BinaryOperator::CreateOr(NewOp, V1);
1898 }
1899
Craig Topperf40110f2014-04-25 05:29:35 +00001900 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001901}
1902
David Majnemer5d1aeba2014-08-21 05:14:48 +00001903/// \brief This helper function folds:
1904///
Craig Toppera074c102017-06-21 18:57:00 +00001905/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001906///
1907/// into:
1908///
1909/// (A & C1) ^ B
1910///
1911/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001912static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1913 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001914 InstCombiner::BuilderTy &Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001915 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1916 if (!CI1)
1917 return nullptr;
1918
1919 Value *V1 = nullptr;
1920 ConstantInt *CI2 = nullptr;
1921 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1922 return nullptr;
1923
1924 APInt Xor = CI1->getValue() ^ CI2->getValue();
1925 if (!Xor.isAllOnesValue())
1926 return nullptr;
1927
1928 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001929 Value *NewOp = Builder.CreateAnd(V1 == A ? B : A, CI1);
David Majnemer5d1aeba2014-08-21 05:14:48 +00001930 return BinaryOperator::CreateXor(NewOp, V1);
1931 }
1932
1933 return nullptr;
1934}
1935
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001936// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1937// here. We should standardize that construct where it is needed or choose some
1938// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001939Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001940 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1942
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001943 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001944 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001945
Craig Toppera4205622017-06-09 03:21:29 +00001946 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001947 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001948
Craig Topper9d4171a2012-12-20 07:09:41 +00001949 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001950 // purpose is to compute bits we don't care about.
1951 if (SimplifyDemandedInstructionBits(I))
1952 return &I;
1953
Sanjay Patele0c26e02017-04-23 22:00:02 +00001954 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001955 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001956 return Xor;
1957
1958 // (A&B)|(A&C) -> A&(B|C) etc
1959 if (Value *V = SimplifyUsingDistributiveLaws(I))
1960 return replaceInstUsesWith(I, V);
1961
Craig Topper95e41422017-07-06 16:24:23 +00001962 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001963 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001964
Craig Topper86173602017-04-04 20:26:25 +00001965 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001966 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1967 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968
Chad Rosiere5819e22016-05-26 14:58:51 +00001969 // Given an OR instruction, check to see if this is a bswap.
1970 if (Instruction *BSwap = MatchBSwap(I))
1971 return BSwap;
1972
Craig Topperafa07c52017-04-09 06:12:41 +00001973 {
1974 Value *A;
1975 const APInt *C;
1976 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1977 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1978 MaskedValueIsZero(Op1, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001979 Value *NOr = Builder.CreateOr(A, Op1);
Craig Topperafa07c52017-04-09 06:12:41 +00001980 NOr->takeName(Op0);
1981 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001982 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001983 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001984
Craig Topperafa07c52017-04-09 06:12:41 +00001985 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1986 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1987 MaskedValueIsZero(Op0, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001988 Value *NOr = Builder.CreateOr(A, Op0);
Craig Topperafa07c52017-04-09 06:12:41 +00001989 NOr->takeName(Op0);
1990 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001991 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001992 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001993 }
1994
Craig Topperafa07c52017-04-09 06:12:41 +00001995 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001996
1997 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00001998 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001999 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2000 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002001 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002002 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2003 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002004 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002005 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002006 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002007 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002008 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002009 ((V1 == B &&
2010 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2011 (V2 == B &&
2012 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002013 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00002014 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002015 // Or commutes, try both ways.
2016 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002017 ((V1 == A &&
2018 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2019 (V2 == A &&
2020 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002021 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00002022 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002023
Chris Lattner95188692010-01-11 06:55:24 +00002024 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002025 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002026 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002027 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002028 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002029 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002030 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002031 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00002032 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00002033 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002034 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002035 }
2036 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002038 // Don't try to form a select if it's unlikely that we'll get rid of at
2039 // least one of the operands. A select is generally more expensive than the
2040 // 'or' that it is replacing.
2041 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2042 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Craig Topperbb4069e2017-07-07 23:16:26 +00002043 if (Value *V = matchSelectFromAndOr(A, C, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002044 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002045 if (Value *V = matchSelectFromAndOr(A, C, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002046 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002047 if (Value *V = matchSelectFromAndOr(C, A, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002048 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002049 if (Value *V = matchSelectFromAndOr(C, A, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002050 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002051 if (Value *V = matchSelectFromAndOr(B, D, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002052 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002053 if (Value *V = matchSelectFromAndOr(B, D, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002054 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002055 if (Value *V = matchSelectFromAndOr(D, B, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002056 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00002057 if (Value *V = matchSelectFromAndOr(D, B, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002058 return replaceInstUsesWith(I, V);
2059 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002060
Benjamin Kramer11743242010-07-12 13:34:22 +00002061 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002062 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2063 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2064 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002065 }
2066 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002067 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2068 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2069 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002070 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002071 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002072 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2073 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2074 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002075 }
2076 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002077 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2078 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2079 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002080 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002081 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002082
David Majnemer42af3602014-07-30 21:26:37 +00002083 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2084 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2085 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002086 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002087
2088 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2089 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2090 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002091 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002092
David Majnemerf1eda232014-08-14 06:41:38 +00002093 // ((B | C) & A) | B -> B | (A & C)
2094 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002095 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00002096
Craig Topperbb4069e2017-07-07 23:16:26 +00002097 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002098 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002099
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002100 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002101 bool SwappedForXor = false;
2102 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002103 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002104 SwappedForXor = true;
2105 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002106
2107 // A | ( A ^ B) -> A | B
2108 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002109 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002110 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2111 if (Op0 == A || Op0 == B)
2112 return BinaryOperator::CreateOr(A, B);
2113
Chad Rosier7813dce2012-04-26 23:29:14 +00002114 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2115 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2116 return BinaryOperator::CreateOr(A, B);
2117
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002118 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002119 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002120 return BinaryOperator::CreateOr(Not, Op0);
2121 }
2122 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002123 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002124 return BinaryOperator::CreateOr(Not, Op0);
2125 }
2126 }
2127
2128 // A | ~(A | B) -> A | ~B
2129 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002130 if (match(Op1, m_Not(m_Value(A))))
2131 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002132 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2133 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2134 B->getOpcode() == Instruction::Xor)) {
2135 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2136 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002137 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002138 return BinaryOperator::CreateOr(Not, Op0);
2139 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002140
Eli Friedmane06535b2012-03-16 00:52:42 +00002141 if (SwappedForXor)
2142 std::swap(Op0, Op1);
2143
David Majnemer3d6f80b2014-11-28 19:58:29 +00002144 {
2145 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2146 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2147 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002148 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002149 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002150
David Majnemer3d6f80b2014-11-28 19:58:29 +00002151 // TODO: Make this recursive; it's a little tricky because an arbitrary
2152 // number of 'or' instructions might have to be created.
2153 Value *X, *Y;
2154 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2155 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002156 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002157 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002158 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002159 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002160 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002161 }
2162 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2163 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002164 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002165 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002166 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002167 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002168 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002169 }
2170 }
2171
Chris Lattner4e8137d2010-02-11 06:26:33 +00002172 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2173 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2174 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002175 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002176 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002177
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002178 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2179 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002180
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002181 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002182 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002183 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002184 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002185 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002186 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002187 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2188
Owen Andersonc237a842010-09-13 17:59:27 +00002189 // Note: If we've gotten to the point of visiting the outer OR, then the
2190 // inner one couldn't be simplified. If it was a constant, then it won't
2191 // be simplified by a later pass either, so we try swapping the inner/outer
2192 // ORs in the hopes that we'll be able to simplify it this way.
2193 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002194 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002195 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2196 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002197 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002198 Inner->takeName(Op0);
2199 return BinaryOperator::CreateOr(Inner, C1);
2200 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002201
Bill Wendling23242092013-02-16 23:41:36 +00002202 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2203 // Since this OR statement hasn't been optimized further yet, we hope
2204 // that this transformation will allow the new ORs to be optimized.
2205 {
Craig Topperf40110f2014-04-25 05:29:35 +00002206 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002207 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2208 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2209 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002210 Value *orTrue = Builder.CreateOr(A, C);
2211 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002212 return SelectInst::Create(X, orTrue, orFalse);
2213 }
2214 }
2215
Craig Topperf40110f2014-04-25 05:29:35 +00002216 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002217}
2218
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002219/// A ^ B can be specified using other logic ops in a variety of patterns. We
2220/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002221static Instruction *foldXorToXor(BinaryOperator &I,
2222 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002223 assert(I.getOpcode() == Instruction::Xor);
2224 Value *Op0 = I.getOperand(0);
2225 Value *Op1 = I.getOperand(1);
2226 Value *A, *B;
2227
2228 // There are 4 commuted variants for each of the basic patterns.
2229
2230 // (A & B) ^ (A | B) -> A ^ B
2231 // (A & B) ^ (B | A) -> A ^ B
2232 // (A | B) ^ (A & B) -> A ^ B
2233 // (A | B) ^ (B & A) -> A ^ B
2234 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2235 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2236 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2237 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2238 I.setOperand(0, A);
2239 I.setOperand(1, B);
2240 return &I;
2241 }
2242
2243 // (A | ~B) ^ (~A | B) -> A ^ B
2244 // (~B | A) ^ (~A | B) -> A ^ B
2245 // (~A | B) ^ (A | ~B) -> A ^ B
2246 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002247 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2248 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2249 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2250 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002251 I.setOperand(0, A);
2252 I.setOperand(1, B);
2253 return &I;
2254 }
2255
2256 // (A & ~B) ^ (~A & B) -> A ^ B
2257 // (~B & A) ^ (~A & B) -> A ^ B
2258 // (~A & B) ^ (A & ~B) -> A ^ B
2259 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002260 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2261 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2262 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2263 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002264 I.setOperand(0, A);
2265 I.setOperand(1, B);
2266 return &I;
2267 }
2268
Craig Topperf60ab472017-07-02 01:15:51 +00002269 // For the remaining cases we need to get rid of one of the operands.
2270 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2271 return nullptr;
2272
2273 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2274 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2275 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2276 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2277 // Complexity sorting ensures the not will be on the right side.
2278 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2279 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2280 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2281 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2282 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2283
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002284 return nullptr;
2285}
2286
Sanjay Patel5e456b92017-05-18 20:53:16 +00002287Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2288 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2289 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2290 LHS->getOperand(1) == RHS->getOperand(0))
2291 LHS->swapOperands();
2292 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2293 LHS->getOperand(1) == RHS->getOperand(1)) {
2294 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2295 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2296 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2297 bool isSigned = LHS->isSigned() || RHS->isSigned();
2298 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2299 }
2300 }
2301
Sanjay Pateladca8252017-06-20 12:40:55 +00002302 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2303 // into those logic ops. That is, try to turn this into an and-of-icmps
2304 // because we have many folds for that pattern.
2305 //
2306 // This is based on a truth table definition of xor:
2307 // X ^ Y --> (X | Y) & !(X & Y)
2308 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2309 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2310 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2311 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2312 // TODO: Independently handle cases where the 'and' side is a constant.
2313 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2314 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2315 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002316 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002317 }
2318 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002319 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002320 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002321 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002322 }
2323 }
2324 }
2325
Sanjay Patel5e456b92017-05-18 20:53:16 +00002326 return nullptr;
2327}
2328
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002329// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2330// here. We should standardize that construct where it is needed or choose some
2331// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002332Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002333 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002334 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2335
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002336 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002337 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002338
Craig Toppera4205622017-06-09 03:21:29 +00002339 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002340 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002341
Craig Topperbb4069e2017-07-07 23:16:26 +00002342 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002343 return NewXor;
2344
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002345 // (A&B)^(A&C) -> A&(B^C) etc
2346 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002347 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002348
Craig Topper9d4171a2012-12-20 07:09:41 +00002349 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002350 // purpose is to compute bits we don't care about.
2351 if (SimplifyDemandedInstructionBits(I))
2352 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002353
Craig Topper95e41422017-07-06 16:24:23 +00002354 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002355 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002356
Sanjay Patel6381db12017-05-02 15:31:40 +00002357 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2358 Value *X, *Y;
2359
2360 // We must eliminate the and/or (one-use) for these transforms to not increase
2361 // the instruction count.
2362 // ~(~X & Y) --> (X | ~Y)
2363 // ~(Y & ~X) --> (X | ~Y)
2364 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002365 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002366 return BinaryOperator::CreateOr(X, NotY);
2367 }
2368 // ~(~X | Y) --> (X & ~Y)
2369 // ~(Y | ~X) --> (X & ~Y)
2370 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002371 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002372 return BinaryOperator::CreateAnd(X, NotY);
2373 }
2374
Sanjay Patel3b863f82017-04-22 18:05:35 +00002375 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002376 BinaryOperator *NotVal;
2377 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2378 if (NotVal->getOpcode() == Instruction::And ||
2379 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002380 // Apply DeMorgan's Law when inverts are free:
2381 // ~(X & Y) --> (~X | ~Y)
2382 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002383 if (IsFreeToInvert(NotVal->getOperand(0),
2384 NotVal->getOperand(0)->hasOneUse()) &&
2385 IsFreeToInvert(NotVal->getOperand(1),
2386 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002387 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2388 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002389 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002390 return BinaryOperator::CreateOr(NotX, NotY);
2391 return BinaryOperator::CreateAnd(NotX, NotY);
2392 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002393 }
2394
2395 // ~(~X >>s Y) --> (X >>s Y)
2396 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2397 return BinaryOperator::CreateAShr(X, Y);
2398
2399 // If we are inverting a right-shifted constant, we may be able to eliminate
2400 // the 'not' by inverting the constant and using the opposite shift type.
2401 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2402 // but we must check that in case that transform has not fired yet.
2403 const APInt *C;
2404 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2405 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2406 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2407 return BinaryOperator::CreateLShr(NotC, Y);
2408 }
2409
2410 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2411 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2412 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2413 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002414 }
2415 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002416
Craig Topper798a19a2017-06-29 00:07:08 +00002417 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002418 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002419 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002420 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2421 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002422 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002423
Craig Topperb5bf0162017-08-06 06:28:41 +00002424 {
2425 const APInt *RHSC;
2426 if (match(Op1, m_APInt(RHSC))) {
2427 Value *V;
2428 const APInt *C;
2429 if (match(Op0, m_Sub(m_APInt(C), m_Value(V)))) {
2430 // ~(c-X) == X-c-1 == X+(-c-1)
2431 if (RHSC->isAllOnesValue()) {
2432 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2433 return BinaryOperator::CreateAdd(V, NewC);
2434 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002435 if (RHSC->isSignMask()) {
2436 // (C - X) ^ signmask -> (C + signmask - X)
2437 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2438 return BinaryOperator::CreateSub(NewC, V);
2439 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002440 } else if (match(Op0, m_Add(m_Value(V), m_APInt(C)))) {
2441 // ~(X-c) --> (-c-1)-X
2442 if (RHSC->isAllOnesValue()) {
2443 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2444 return BinaryOperator::CreateSub(NewC, V);
2445 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002446 if (RHSC->isSignMask()) {
2447 // (X + C) ^ signmask -> (X + C + signmask)
2448 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2449 return BinaryOperator::CreateAdd(V, NewC);
2450 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002451 }
2452 }
2453 }
2454
Craig Topper9d1821b2017-04-09 06:12:31 +00002455 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002457 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9cbdbef2017-08-06 22:17:21 +00002458 if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002459 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002460 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2461 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002462 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002463 // Anything in both C1 and C2 is known to be zero, remove it from
2464 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002465 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002466 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002467 ConstantExpr::getNot(CommonBits));
2468 Worklist.Add(Op0I);
2469 I.setOperand(0, Op0I->getOperand(0));
2470 I.setOperand(1, NewRHS);
2471 return &I;
2472 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002473 } else if (Op0I->getOpcode() == Instruction::LShr) {
2474 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2475 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002476 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002477 ConstantInt *C1;
2478 if (Op0I->hasOneUse() &&
2479 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2480 E1->getOpcode() == Instruction::Xor &&
2481 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2482 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002483 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002484 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2485 FoldConst ^= C3->getValue();
2486 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002487 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002488 Opnd0->takeName(Op0I);
2489 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2490 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2491
2492 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2493 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002494 }
2495 }
2496 }
Craig Topper86173602017-04-04 20:26:25 +00002497 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002498
Craig Topper86173602017-04-04 20:26:25 +00002499 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002500 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2501 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002502
Craig Topper76394602017-04-10 06:53:23 +00002503 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002504 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002505 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002506 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002507 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002508 std::swap(A, B);
2509 }
2510 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002511 I.swapOperands(); // Simplified below.
2512 std::swap(Op0, Op1);
2513 }
Craig Topper76394602017-04-10 06:53:23 +00002514 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002516 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002517 std::swap(A, B);
2518 }
2519 if (B == Op0) { // A^(B&A) -> (B&A)^A
2520 I.swapOperands(); // Simplified below.
2521 std::swap(Op0, Op1);
2522 }
2523 }
2524 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002525
Craig Topper76394602017-04-10 06:53:23 +00002526 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002527 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002528 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002529 if (A == Op1) // (B|A)^B == (A|B)^B
2530 std::swap(A, B);
2531 if (B == Op1) // (A|B)^B == A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00002532 return BinaryOperator::CreateAnd(A, Builder.CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002533 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002534 if (A == Op1) // (A&B)^A -> (B&A)^A
2535 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002536 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002537 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002538 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Craig Topperbb4069e2017-07-07 23:16:26 +00002539 return BinaryOperator::CreateAnd(Builder.CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002540 }
2541 }
2542 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002543
Craig Topper76394602017-04-10 06:53:23 +00002544 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002545 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002546 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002547 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2548 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002549 if (D == A)
2550 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002551 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002552 if (D == B)
2553 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002554 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002555 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002556 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002557 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2558 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002559 if (D == A)
2560 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002561 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002562 if (D == B)
2563 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002564 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002565 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002566 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002567 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002568 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002569 return BinaryOperator::CreateOr(A, B);
2570 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002571 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002572 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002573 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002574 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002575
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002576 // (A & ~B) ^ ~A -> ~(A & B)
2577 // (~B & A) ^ ~A -> ~(A & B)
2578 Value *A, *B;
2579 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002580 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002581 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002582
Sanjay Patel5e456b92017-05-18 20:53:16 +00002583 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2584 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2585 if (Value *V = foldXorOfICmps(LHS, RHS))
2586 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002588 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2589 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002590
Craig Topperf40110f2014-04-25 05:29:35 +00002591 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002592}