blob: 0f034107b3d1355a2b8e7e71cfa5f42f7bd5b849 [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,
57 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;
61 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,
Chris Lattner067459c2010-03-05 08:46: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);
Chris Lattner067459c2010-03-05 08:46:26 +000075 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
79/// \param I Binary operator to transform.
80/// \return Pointer to node that must replace the original binary operator, or
81/// null pointer if no transformation was made.
82Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
Craig Topperc6948c22017-07-03 05:54:11 +000083 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
84
Craig Topper766ce6e2017-07-03 05:54:15 +000085 Value *NewLHS;
86 if (!match(I.getOperand(0), m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000087 return nullptr;
88
Craig Topper766ce6e2017-07-03 05:54:15 +000089 Value *NewRHS;
90 const APInt *C;
91
92 if (match(I.getOperand(1), m_BSwap(m_Value(NewRHS)))) {
93 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
94 // NewRHS initialized by the matcher.
95 } else if (match(I.getOperand(1), m_APInt(C))) {
96 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
97 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
98 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000099 return nullptr;
100
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000101 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000102 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
103 I.getType());
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000104 return Builder->CreateCall(F, BinOp);
105}
106
Sanjay Patel18549272015-09-08 18:24:36 +0000107/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000108/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
109Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000110 ConstantInt *OpRHS,
111 ConstantInt *AndRHS,
112 BinaryOperator &TheAnd) {
113 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000114 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000115 if (!Op->isShift())
116 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
117
118 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000119 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000120 case Instruction::Xor:
121 if (Op->hasOneUse()) {
122 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
123 Value *And = Builder->CreateAnd(X, AndRHS);
124 And->takeName(Op);
125 return BinaryOperator::CreateXor(And, Together);
126 }
127 break;
128 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000129 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000130 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
131 if (TogetherCI && !TogetherCI->isZero()){
132 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
133 // NOTE: This reduces the number of bits set in the & mask, which
134 // can expose opportunities for store narrowing.
135 Together = ConstantExpr::getXor(AndRHS, Together);
136 Value *And = Builder->CreateAnd(X, Together);
137 And->takeName(Op);
138 return BinaryOperator::CreateOr(And, OpRHS);
139 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000140 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000141
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142 break;
143 case Instruction::Add:
144 if (Op->hasOneUse()) {
145 // Adding a one to a single bit bit-field should be turned into an XOR
146 // of the bit. First thing to check is to see if this AND is with a
147 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000148 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000149
150 // If there is only one bit set.
151 if (AndRHSV.isPowerOf2()) {
152 // Ok, at this point, we know that we are masking the result of the
153 // ADD down to exactly one bit. If the constant we are adding has
154 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000155 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000156
157 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000158 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000159 // If not, the only thing that can effect the output of the AND is
160 // the bit specified by AndRHSV. If that bit is set, the effect of
161 // the XOR is to toggle the bit. If it is clear, then the ADD has
162 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000163 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000164 TheAnd.setOperand(0, X);
165 return &TheAnd;
166 } else {
167 // Pull the XOR out of the AND.
168 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
169 NewAnd->takeName(Op);
170 return BinaryOperator::CreateXor(NewAnd, AndRHS);
171 }
172 }
173 }
174 }
175 break;
176
177 case Instruction::Shl: {
178 // We know that the AND will not produce any of the bits shifted in, so if
179 // the anded constant includes them, clear them now!
180 //
181 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
182 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
183 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000184 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000185
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000186 if (CI->getValue() == ShlMask)
187 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000188 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000189
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000190 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000191 TheAnd.setOperand(1, CI);
192 return &TheAnd;
193 }
194 break;
195 }
196 case Instruction::LShr: {
197 // We know that the AND will not produce any of the bits shifted in, so if
198 // the anded constant includes them, clear them now! This only applies to
199 // unsigned shifts, because a signed shr may bring in set bits!
200 //
201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
203 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000204 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000205
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000206 if (CI->getValue() == ShrMask)
207 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000208 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000209
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000210 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000211 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
212 return &TheAnd;
213 }
214 break;
215 }
216 case Instruction::AShr:
217 // Signed shr.
218 // See if this is shifting in some sign extension, then masking it out
219 // with an and.
220 if (Op->hasOneUse()) {
221 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
222 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
223 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000224 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000225 if (C == AndRHS) { // Masking out bits shifted in.
226 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
227 // Make the argument unsigned.
228 Value *ShVal = Op->getOperand(0);
229 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
230 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
231 }
232 }
233 break;
234 }
Craig Topperf40110f2014-04-25 05:29:35 +0000235 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000236}
237
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000238/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000239/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
240/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000241Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000242 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000243 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000244 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000245
Sanjay Patel85d79742016-08-31 19:49:56 +0000246 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000247 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000248 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000249
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000250 // V >= Min && V < Hi --> V < Hi
251 // V < Min || V >= Hi --> V >= Hi
252 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000253 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000254 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000255 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000256 }
257
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000258 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
259 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000260 Value *VMinusLo =
261 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
262 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000263 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000264}
265
Sanjay Patel77bf6222017-04-03 16:53:12 +0000266/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
267/// that can be simplified.
268/// One of A and B is considered the mask. The other is the value. This is
269/// described as the "AMask" or "BMask" part of the enum. If the enum contains
270/// only "Mask", then both A and B can be considered masks. If A is the mask,
271/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
272/// If both A and C are constants, this proof is also easy.
273/// For the following explanations, we assume that A is the mask.
274///
275/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
276/// bits of A are set in B.
277/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
278///
279/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
280/// bits of A are cleared in B.
281/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
282///
283/// "Mixed" declares that (A & B) == C and C might or might not contain any
284/// number of one bits and zero bits.
285/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
286///
287/// "Not" means that in above descriptions "==" should be replaced by "!=".
288/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
289///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000290/// If the mask A contains a single bit, then the following is equivalent:
291/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
292/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
293enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000294 AMask_AllOnes = 1,
295 AMask_NotAllOnes = 2,
296 BMask_AllOnes = 4,
297 BMask_NotAllOnes = 8,
298 Mask_AllZeros = 16,
299 Mask_NotAllZeros = 32,
300 AMask_Mixed = 64,
301 AMask_NotMixed = 128,
302 BMask_Mixed = 256,
303 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000304};
305
Sanjay Patel77bf6222017-04-03 16:53:12 +0000306/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
307/// satisfies.
308static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
309 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000310 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
311 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
312 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000313 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
314 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
315 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
316 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000317 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000318 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000319 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
320 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
321 if (IsAPow2)
322 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
323 : (AMask_AllOnes | AMask_Mixed));
324 if (IsBPow2)
325 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
326 : (BMask_AllOnes | BMask_Mixed));
327 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000328 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000329
Owen Anderson3fe002d2010-09-08 22:16:17 +0000330 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000331 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
332 : (AMask_NotAllOnes | AMask_NotMixed));
333 if (IsAPow2)
334 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
335 : (Mask_AllZeros | AMask_Mixed));
336 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
337 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000338 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000339
Craig Topperae48cb22012-12-20 07:15:54 +0000340 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000341 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
342 : (BMask_NotAllOnes | BMask_NotMixed));
343 if (IsBPow2)
344 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
345 : (Mask_AllZeros | BMask_Mixed));
346 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
347 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000348 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000349
350 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000351}
352
Tim Northoverc0756c42013-09-04 11:57:13 +0000353/// Convert an analysis of a masked ICmp into its equivalent if all boolean
354/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
355/// is adjacent to the corresponding normal flag (recording ==), this just
356/// involves swapping those bits over.
357static unsigned conjugateICmpMask(unsigned Mask) {
358 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000359 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
360 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000361 << 1;
362
Sanjay Patel77bf6222017-04-03 16:53:12 +0000363 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
364 AMask_NotMixed | BMask_NotMixed))
365 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000366
367 return NewMask;
368}
369
Sanjay Patel77bf6222017-04-03 16:53:12 +0000370/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
371/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
372/// RHS satisfy.
373static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
374 Value *&D, Value *&E, ICmpInst *LHS,
375 ICmpInst *RHS,
376 ICmpInst::Predicate &PredL,
377 ICmpInst::Predicate &PredR) {
378 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
379 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000380 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000381 if (LHS->getOperand(0)->getType()->isVectorTy())
382 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000383
384 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000385 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000386 // and L11 & L12 == L21 & L22. The same goes for RHS.
387 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000388 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000389 // above.
390 Value *L1 = LHS->getOperand(0);
391 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000392 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000393 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000394 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000395 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000396 } else {
397 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000398 if (!L1->getType()->isIntegerTy()) {
399 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000400 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000401 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
402 // Any icmp can be viewed as being trivially masked; if it allows us to
403 // remove one, it's worth it.
404 L11 = L1;
405 L12 = Constant::getAllOnesValue(L1->getType());
406 }
407
408 if (!L2->getType()->isIntegerTy()) {
409 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000410 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000411 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
412 L21 = L2;
413 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000414 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000416
417 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000418 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000419 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000420
421 Value *R1 = RHS->getOperand(0);
422 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000423 Value *R11, *R12;
424 bool Ok = false;
425 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000426 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000427 A = R11;
428 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000429 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000430 A = R12;
431 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000432 } else {
433 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000434 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000435 E = R2;
436 R1 = nullptr;
437 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000438 } else if (R1->getType()->isIntegerTy()) {
439 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
440 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000441 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000442 R11 = R1;
443 R12 = Constant::getAllOnesValue(R1->getType());
444 }
445
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000446 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000447 A = R11;
448 D = R12;
449 E = R2;
450 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000451 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000452 A = R12;
453 D = R11;
454 E = R2;
455 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000456 }
457 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000458
459 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000460 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000461 return 0;
462
Chad Rosier58919cc2016-05-09 21:37:43 +0000463 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000464 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000465 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
466 R11 = R2;
467 R12 = Constant::getAllOnesValue(R2->getType());
468 }
469
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000470 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000471 A = R11;
472 D = R12;
473 E = R1;
474 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000475 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000476 A = R12;
477 D = R11;
478 E = R1;
479 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000480 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000482 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000483 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000484 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000485 return 0;
486
487 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000488 B = L12;
489 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000490 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000491 B = L11;
492 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000493 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000494 B = L22;
495 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000496 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000497 B = L21;
498 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000499 }
500
Sanjay Patel77bf6222017-04-03 16:53:12 +0000501 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
502 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000503 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000504}
Sanjay Patel18549272015-09-08 18:24:36 +0000505
506/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
507/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000508static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
509 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000510 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000511 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
512 unsigned Mask =
513 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
514 if (Mask == 0)
515 return nullptr;
516
517 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
518 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000519
Tim Northoverc0756c42013-09-04 11:57:13 +0000520 // In full generality:
521 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
522 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
523 //
524 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
525 // equivalent to (icmp (A & X) !Op Y).
526 //
527 // Therefore, we can pretend for the rest of this function that we're dealing
528 // with the conjunction, provided we flip the sense of any comparisons (both
529 // input and output).
530
531 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000532 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000533 if (!IsAnd) {
534 // Convert the masking analysis into its equivalent with negated
535 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000536 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000537 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000538
Sanjay Patel77bf6222017-04-03 16:53:12 +0000539 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000540 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000541 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000542 Value *NewOr = Builder->CreateOr(B, D);
543 Value *NewAnd = Builder->CreateAnd(A, NewOr);
544 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000545 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000546 // with B and D, having a single bit set.
547 Value *Zero = Constant::getNullValue(A->getType());
548 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000549 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000550 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000551 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000552 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000553 Value *NewOr = Builder->CreateOr(B, D);
554 Value *NewAnd = Builder->CreateAnd(A, NewOr);
555 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000556 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000557 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000558 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000560 Value *NewAnd1 = Builder->CreateAnd(B, D);
561 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
562 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000563 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000564
565 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000566 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000567 // easy cases for now" decision.
568 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000569 if (!BCst)
570 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000571 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000572 if (!DCst)
573 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000574
Sanjay Patel77bf6222017-04-03 16:53:12 +0000575 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000576 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
577 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
578 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
579 // Only valid if one of the masks is a superset of the other (check "B&D" is
580 // the same as either B or D).
581 APInt NewMask = BCst->getValue() & DCst->getValue();
582
583 if (NewMask == BCst->getValue())
584 return LHS;
585 else if (NewMask == DCst->getValue())
586 return RHS;
587 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000588
589 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000590 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
591 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
592 // Only valid if one of the masks is a superset of the other (check "B|D" is
593 // the same as either B or D).
594 APInt NewMask = BCst->getValue() | DCst->getValue();
595
596 if (NewMask == BCst->getValue())
597 return LHS;
598 else if (NewMask == DCst->getValue())
599 return RHS;
600 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000601
602 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000603 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000604 // We already know that B & C == C && D & E == E.
605 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
606 // C and E, which are shared by both the mask B and the mask D, don't
607 // contradict, then we can transform to
608 // -> (icmp eq (A & (B|D)), (C|E))
609 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000610 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000611 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000612 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000613 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000614 if (!CCst)
615 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000616 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000617 if (!ECst)
618 return nullptr;
619 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000620 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000621 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000622 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000623
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000624 // If there is a conflict, we should actually return a false for the
625 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000626 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000627 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000628 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000629
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000630 Value *NewOr1 = Builder->CreateOr(B, D);
631 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
632 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
633 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000634 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000635
Craig Topperf40110f2014-04-25 05:29:35 +0000636 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000637}
638
Erik Ecksteind1817522014-12-03 10:39:15 +0000639/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
640/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
641/// If \p Inverted is true then the check is for the inverted range, e.g.
642/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
643Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
644 bool Inverted) {
645 // Check the lower range comparison, e.g. x >= 0
646 // InstCombine already ensured that if there is a constant it's on the RHS.
647 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
648 if (!RangeStart)
649 return nullptr;
650
651 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
652 Cmp0->getPredicate());
653
654 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
655 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
656 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
657 return nullptr;
658
659 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
660 Cmp1->getPredicate());
661
662 Value *Input = Cmp0->getOperand(0);
663 Value *RangeEnd;
664 if (Cmp1->getOperand(0) == Input) {
665 // For the upper range compare we have: icmp x, n
666 RangeEnd = Cmp1->getOperand(1);
667 } else if (Cmp1->getOperand(1) == Input) {
668 // For the upper range compare we have: icmp n, x
669 RangeEnd = Cmp1->getOperand(0);
670 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
671 } else {
672 return nullptr;
673 }
674
675 // Check the upper range comparison, e.g. x < n
676 ICmpInst::Predicate NewPred;
677 switch (Pred1) {
678 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
679 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
680 default: return nullptr;
681 }
682
683 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000684 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
685 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000686 return nullptr;
687
688 if (Inverted)
689 NewPred = ICmpInst::getInversePredicate(NewPred);
690
691 return Builder->CreateICmp(NewPred, Input, RangeEnd);
692}
693
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000694static Value *
695foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
696 bool JoinedByAnd,
697 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000698 Value *X = LHS->getOperand(0);
699 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000700 return nullptr;
701
Sanjay Patelef9f5862017-04-15 17:55:06 +0000702 const APInt *C1, *C2;
703 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
704 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000705 return nullptr;
706
707 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
708 ICmpInst::Predicate Pred = LHS->getPredicate();
709 if (Pred != RHS->getPredicate())
710 return nullptr;
711 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
712 return nullptr;
713 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
714 return nullptr;
715
716 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000717 if (C1->ugt(*C2))
718 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000719
Sanjay Patelef9f5862017-04-15 17:55:06 +0000720 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000721 if (Xor.isPowerOf2()) {
722 // If LHSC and RHSC differ by only one bit, then set that bit in X and
723 // compare against the larger constant:
724 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
725 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
726 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
727 // 'and' because that may lead to smaller codegen from a smaller constant.
728 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000729 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000730 }
731
732 // Special case: get the ordering right when the values wrap around zero.
733 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000734 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000735 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000736
Sanjay Patelef9f5862017-04-15 17:55:06 +0000737 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000738 // (X == 13 || X == 14) --> X - 13 <=u 1
739 // (X != 13 && X != 14) --> X - 13 >u 1
740 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000741 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000742 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
743 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
744 }
745
746 return nullptr;
747}
748
Craig Topperda6ea0d2017-06-16 05:10:37 +0000749// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
750// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
751Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
752 bool JoinedByAnd,
753 Instruction &CxtI) {
754 ICmpInst::Predicate Pred = LHS->getPredicate();
755 if (Pred != RHS->getPredicate())
756 return nullptr;
757 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
758 return nullptr;
759 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
760 return nullptr;
761
762 // TODO support vector splats
763 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
764 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
765 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
766 return nullptr;
767
768 Value *A, *B, *C, *D;
769 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
770 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
771 if (A == D || B == D)
772 std::swap(C, D);
773 if (B == C)
774 std::swap(A, B);
775
776 if (A == C &&
777 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
778 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
779 Value *Mask = Builder->CreateOr(B, D);
780 Value *Masked = Builder->CreateAnd(A, Mask);
781 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
782 return Builder->CreateICmp(NewPred, Masked, Mask);
783 }
784 }
785
786 return nullptr;
787}
788
Sanjay Patel18549272015-09-08 18:24:36 +0000789/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000790Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
791 Instruction &CxtI) {
792 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
793 // if K1 and K2 are a one-bit mask.
794 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
795 return V;
796
Sanjay Patel519a87a2017-04-05 17:38:34 +0000797 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000798
799 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000800 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000801 if (LHS->getOperand(0) == RHS->getOperand(1) &&
802 LHS->getOperand(1) == RHS->getOperand(0))
803 LHS->swapOperands();
804 if (LHS->getOperand(0) == RHS->getOperand(0) &&
805 LHS->getOperand(1) == RHS->getOperand(1)) {
806 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
807 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
808 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000809 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000810 }
811 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000812
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000813 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000814 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000815 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000816
Erik Ecksteind1817522014-12-03 10:39:15 +0000817 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
818 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
819 return V;
820
821 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
822 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
823 return V;
824
Sanjay Patelef9f5862017-04-15 17:55:06 +0000825 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
826 return V;
827
Chris Lattner0a8191e2010-01-05 07:50:36 +0000828 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000829 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000830 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
831 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
832 if (!LHSC || !RHSC)
833 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000834
Sanjay Patel519a87a2017-04-05 17:38:34 +0000835 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000837 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000838 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000839 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
840 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000841 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000842 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000843 }
844 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000845
Benjamin Kramer101720f2011-04-28 20:09:57 +0000846 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000847 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000848 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000849 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
850 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000851 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000852 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000853
854 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000855 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000856 if (match(RHS0, m_Trunc(m_Value(V))) &&
857 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000858 SmallC = RHSC;
859 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000860 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
861 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000862 SmallC = LHSC;
863 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000864 }
865
Sanjay Patel519a87a2017-04-05 17:38:34 +0000866 if (SmallC && BigC) {
867 unsigned BigBitSize = BigC->getType()->getBitWidth();
868 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000869
870 // Check that the low bits are zero.
871 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000872 if ((Low & AndC->getValue()).isNullValue() &&
873 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000874 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
875 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
876 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
877 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000878 }
879 }
880 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000881
Chris Lattner0a8191e2010-01-05 07:50:36 +0000882 // From here on, we only handle:
883 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000884 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000885 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000886
Sanjay Patel519a87a2017-04-05 17:38:34 +0000887 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
888 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
889 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
890 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
891 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000892 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000893
Chris Lattner0a8191e2010-01-05 07:50:36 +0000894 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000895 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000896 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000897
Chris Lattner0a8191e2010-01-05 07:50:36 +0000898 // Ensure that the larger constant is on the RHS.
899 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000900 if (CmpInst::isSigned(PredL) ||
901 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000902 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000903 else
904 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000905
Chris Lattner0a8191e2010-01-05 07:50:36 +0000906 if (ShouldSwap) {
907 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000908 std::swap(LHSC, RHSC);
909 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000910 }
911
Dan Gohman4a618822010-02-10 16:03:48 +0000912 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000913 // comparing a value against two constants and and'ing the result
914 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000915 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
916 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000918 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000919
Sanjay Patel519a87a2017-04-05 17:38:34 +0000920 switch (PredL) {
921 default:
922 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000923 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000924 switch (PredR) {
925 default:
926 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000928 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000929 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000930 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000931 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000932 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000933 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000935 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000936 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000937 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000938 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000939 // Potential folds for this case should already be handled.
940 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000941 }
942 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000944 switch (PredR) {
945 default:
946 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000947 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000948 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000949 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000950 break; // (X u> 13 & X != 15) -> no change
951 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000952 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
953 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000954 }
955 break;
956 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000957 switch (PredR) {
958 default:
959 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000961 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000962 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000963 break; // (X s> 13 & X != 15) -> no change
964 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000965 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000966 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 }
968 break;
969 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000970
Craig Topperf40110f2014-04-25 05:29:35 +0000971 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972}
973
Sanjay Patel18549272015-09-08 18:24:36 +0000974/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
975/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000976Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000977 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
978 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
979 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
980
981 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
982 // Swap RHS operands to match LHS.
983 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
984 std::swap(Op1LHS, Op1RHS);
985 }
986
987 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
988 // Suppose the relation between x and y is R, where R is one of
989 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
990 // testing the desired relations.
991 //
992 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
993 // bool(R & CC0) && bool(R & CC1)
994 // = bool((R & CC0) & (R & CC1))
995 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
996 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
997 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
998 Builder);
999
Chris Lattner0a8191e2010-01-05 07:50:36 +00001000 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1001 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001002 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001003 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001004
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1006 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1007 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1008 // If either of the constants are nans, then the whole thing returns
1009 // false.
1010 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001011 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001012 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001013 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001014
Chris Lattner0a8191e2010-01-05 07:50:36 +00001015 // Handle vector zeros. This occurs because the canonical form of
1016 // "fcmp ord x,x" is "fcmp ord x, 0".
1017 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1018 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001019 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001020 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001022
Craig Topperf40110f2014-04-25 05:29:35 +00001023 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024}
1025
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001026/// Match De Morgan's Laws:
1027/// (~A & ~B) == (~(A | B))
1028/// (~A | ~B) == (~(A & B))
1029static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001030 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001031 auto Opcode = I.getOpcode();
1032 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1033 "Trying to match De Morgan's Laws with something other than and/or");
1034
Sanjay Patel7caaa792017-05-09 20:05:05 +00001035 // Flip the logic operation.
1036 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1037
1038 Value *A, *B;
1039 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1040 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1041 !IsFreeToInvert(A, A->hasOneUse()) &&
1042 !IsFreeToInvert(B, B->hasOneUse())) {
1043 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1044 return BinaryOperator::CreateNot(AndOr);
1045 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001046
1047 return nullptr;
1048}
1049
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001050bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1051 Value *CastSrc = CI->getOperand(0);
1052
1053 // Noop casts and casts of constants should be eliminated trivially.
1054 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1055 return false;
1056
1057 // If this cast is paired with another cast that can be eliminated, we prefer
1058 // to have it eliminated.
1059 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1060 if (isEliminableCastPair(PrecedingCI, CI))
1061 return false;
1062
1063 // If this is a vector sext from a compare, then we don't want to break the
1064 // idiom where each element of the extended vector is either zero or all ones.
1065 if (CI->getOpcode() == Instruction::SExt &&
1066 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1067 return false;
1068
1069 return true;
1070}
1071
Sanjay Patel60312bc42016-09-12 00:16:23 +00001072/// Fold {and,or,xor} (cast X), C.
1073static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1074 InstCombiner::BuilderTy *Builder) {
1075 Constant *C;
1076 if (!match(Logic.getOperand(1), m_Constant(C)))
1077 return nullptr;
1078
1079 auto LogicOpc = Logic.getOpcode();
1080 Type *DestTy = Logic.getType();
1081 Type *SrcTy = Cast->getSrcTy();
1082
Sanjay Pateld1e81192017-06-22 15:46:54 +00001083 // Move the logic operation ahead of a zext if the constant is unchanged in
1084 // the smaller source type. Performing the logic in a smaller type may provide
1085 // more information to later folds, and the smaller logic instruction may be
1086 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001087 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001088 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1089 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1090 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1091 if (ZextTruncC == C) {
1092 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1093 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1094 return new ZExtInst(NewOp, DestTy);
1095 }
1096 }
1097
1098 return nullptr;
1099}
1100
1101/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001102Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001103 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001104 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001105
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001107 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001108 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001109 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001110
Sanjay Patel9bba7502016-03-03 19:19:04 +00001111 // This must be a cast from an integer or integer vector source type to allow
1112 // transformation of the logic operation to the source type.
1113 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001114 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001115 if (!SrcTy->isIntOrIntVectorTy())
1116 return nullptr;
1117
Sanjay Patel60312bc42016-09-12 00:16:23 +00001118 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1119 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001120
Sanjay Patel9bba7502016-03-03 19:19:04 +00001121 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1122 if (!Cast1)
1123 return nullptr;
1124
1125 // Both operands of the logic operation are casts. The casts must be of the
1126 // same type for reduction.
1127 auto CastOpcode = Cast0->getOpcode();
1128 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001129 return nullptr;
1130
1131 Value *Cast0Src = Cast0->getOperand(0);
1132 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001133
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001134 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001135 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001136 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1137 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001138 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001139 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001140
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001141 // For now, only 'and'/'or' have optimizations after this.
1142 if (LogicOpc == Instruction::Xor)
1143 return nullptr;
1144
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001145 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001146 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001147 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1148 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1149 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001150 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001151 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001152 if (Res)
1153 return CastInst::Create(CastOpcode, Res, DestTy);
1154 return nullptr;
1155 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001156
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001157 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001158 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001159 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1160 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1161 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001162 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1163 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001164 if (Res)
1165 return CastInst::Create(CastOpcode, Res, DestTy);
1166 return nullptr;
1167 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001168
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001169 return nullptr;
1170}
1171
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001172static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1173 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1174
1175 // Canonicalize SExt or Not to the LHS
1176 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1177 std::swap(Op0, Op1);
1178 }
1179
1180 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1181 Value *X = nullptr;
1182 if (match(Op0, m_SExt(m_Value(X))) &&
1183 X->getType()->getScalarType()->isIntegerTy(1)) {
1184 Value *Zero = Constant::getNullValue(Op1->getType());
1185 return SelectInst::Create(X, Op1, Zero);
1186 }
1187
1188 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1189 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1190 X->getType()->getScalarType()->isIntegerTy(1)) {
1191 Value *Zero = Constant::getNullValue(Op0->getType());
1192 return SelectInst::Create(X, Zero, Op1);
1193 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001194
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001195 return nullptr;
1196}
1197
Sanjay Patele0c26e02017-04-23 22:00:02 +00001198static Instruction *foldAndToXor(BinaryOperator &I,
1199 InstCombiner::BuilderTy &Builder) {
1200 assert(I.getOpcode() == Instruction::And);
1201 Value *Op0 = I.getOperand(0);
1202 Value *Op1 = I.getOperand(1);
1203 Value *A, *B;
1204
1205 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1206 // (A | B) & ~(A & B) --> A ^ B
1207 // (A | B) & ~(B & A) --> A ^ B
1208 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1209 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1210 return BinaryOperator::CreateXor(A, B);
1211
1212 // (A | ~B) & (~A | B) --> ~(A ^ B)
1213 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1214 // (~B | A) & (~A | B) --> ~(A ^ B)
1215 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001216 if (Op0->hasOneUse() || Op1->hasOneUse())
1217 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1218 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1219 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001220
1221 return nullptr;
1222}
1223
1224static Instruction *foldOrToXor(BinaryOperator &I,
1225 InstCombiner::BuilderTy &Builder) {
1226 assert(I.getOpcode() == Instruction::Or);
1227 Value *Op0 = I.getOperand(0);
1228 Value *Op1 = I.getOperand(1);
1229 Value *A, *B;
1230
1231 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1232 // (A & B) | ~(A | B) --> ~(A ^ B)
1233 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001234 if (Op0->hasOneUse() || Op1->hasOneUse())
1235 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1236 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1237 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001238
1239 // (A & ~B) | (~A & B) --> A ^ B
1240 // (A & ~B) | (B & ~A) --> A ^ B
1241 // (~B & A) | (~A & B) --> A ^ B
1242 // (~B & A) | (B & ~A) --> A ^ B
1243 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1244 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1245 return BinaryOperator::CreateXor(A, B);
1246
1247 return nullptr;
1248}
1249
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001250// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1251// here. We should standardize that construct where it is needed or choose some
1252// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001253Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001254 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1256
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001257 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001258 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001259
Craig Toppera4205622017-06-09 03:21:29 +00001260 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001261 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262
Craig Topper9d4171a2012-12-20 07:09:41 +00001263 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001264 // purpose is to compute bits we don't care about.
1265 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001266 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001267
Sanjay Patele0c26e02017-04-23 22:00:02 +00001268 // Do this before using distributive laws to catch simple and/or/not patterns.
1269 if (Instruction *Xor = foldAndToXor(I, *Builder))
1270 return Xor;
1271
1272 // (A|B)&(A|C) -> A|(B&C) etc
1273 if (Value *V = SimplifyUsingDistributiveLaws(I))
1274 return replaceInstUsesWith(I, V);
1275
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001276 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001277 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001278
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1280 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001281
1282 // Optimize a variety of ((val OP C1) & C2) combinations...
1283 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1284 Value *Op0LHS = Op0I->getOperand(0);
1285 Value *Op0RHS = Op0I->getOperand(1);
1286 switch (Op0I->getOpcode()) {
1287 default: break;
1288 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001289 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001290 // If the mask is only needed on one incoming arm, push it up.
1291 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001292
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001293 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001294 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001295 // Not masking anything out for the LHS, move to RHS.
1296 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1297 Op0RHS->getName()+".masked");
1298 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1299 }
1300 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001301 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001302 // Not masking anything out for the RHS, move to LHS.
1303 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1304 Op0LHS->getName()+".masked");
1305 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1306 }
1307
1308 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001309 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001311 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001312 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001313 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1314
Chris Lattner0a8191e2010-01-05 07:50:36 +00001315 break;
1316
1317 case Instruction::Shl:
1318 case Instruction::LShr:
1319 // (1 << x) & 1 --> zext(x == 0)
1320 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001321 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322 Value *NewICmp =
1323 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1324 return new ZExtInst(NewICmp, I.getType());
1325 }
1326 break;
1327 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001328
David Majnemerde55c602017-01-17 18:08:06 +00001329 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1330 // of X and OP behaves well when given trunc(C1) and X.
1331 switch (Op0I->getOpcode()) {
1332 default:
1333 break;
1334 case Instruction::Xor:
1335 case Instruction::Or:
1336 case Instruction::Mul:
1337 case Instruction::Add:
1338 case Instruction::Sub:
1339 Value *X;
1340 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001341 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001342 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1343 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1344 Value *BinOp;
1345 if (isa<ZExtInst>(Op0LHS))
1346 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1347 else
1348 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1349 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1350 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1351 return new ZExtInst(And, I.getType());
1352 }
1353 }
1354 }
1355
Chris Lattner0a8191e2010-01-05 07:50:36 +00001356 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1357 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1358 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001359 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001360
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001361 // If this is an integer truncation, and if the source is an 'and' with
1362 // immediate, transform it. This frequently occurs for bitfield accesses.
1363 {
Craig Topperf40110f2014-04-25 05:29:35 +00001364 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001365 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1366 // Change: and (trunc (and X, YC) to T), C2
1367 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001368 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001369 // other simplifications.
1370 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1371 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1372 C3 = ConstantExpr::getAnd(C3, AndRHS);
1373 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001374 }
1375 }
Craig Topper86173602017-04-04 20:26:25 +00001376 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001377
Craig Topper86173602017-04-04 20:26:25 +00001378 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001379 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1380 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001381
Sanjay Patel7caaa792017-05-09 20:05:05 +00001382 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001383 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001384
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001386 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001387 // A&(A^B) => A & ~B
1388 {
1389 Value *tmpOp0 = Op0;
1390 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001391 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001392 if (A == Op1 || B == Op1 ) {
1393 tmpOp1 = Op0;
1394 tmpOp0 = Op1;
1395 // Simplify below
1396 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001397 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001398
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001399 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001400 if (B == tmpOp0) {
1401 std::swap(A, B);
1402 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001403 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001404 // A is originally -1 (or a vector of -1 and undefs), then we enter
1405 // an endless loop. By checking that A is non-constant we ensure that
1406 // we will never get to the loop.
1407 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001408 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001410 }
1411
1412 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001413 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001415 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001416 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001417
1418 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1419 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1420 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001421 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001422 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1423
1424 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1425 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1426 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001427 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001428 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001429
1430 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001431 // (A | B) & (B ^ (~A)) -> (A & B)
1432 // (B | A) & ((~A) ^ B) -> (A & B)
1433 // (B | A) & (B ^ (~A)) -> (A & B)
1434 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1435 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001436 return BinaryOperator::CreateAnd(A, B);
1437
1438 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001439 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001440 // (B ^ (~A)) & (A | B) -> (A & B)
1441 // (B ^ (~A)) & (B | A) -> (A & B)
1442 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001443 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001444 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001445 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001446
David Majnemer5e96f1b2014-08-30 06:18:20 +00001447 {
1448 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1449 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1450 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001451 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001452 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001453
David Majnemer5e96f1b2014-08-30 06:18:20 +00001454 // TODO: Make this recursive; it's a little tricky because an arbitrary
1455 // number of 'and' instructions might have to be created.
1456 Value *X, *Y;
1457 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1458 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001459 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001460 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001461 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001462 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001463 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001464 }
1465 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1466 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001467 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001468 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001469 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001470 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001472 }
1473 }
1474
Chris Lattner4e8137d2010-02-11 06:26:33 +00001475 // If and'ing two fcmp, try combine them into one.
1476 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1477 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001478 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001480
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001481 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1482 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001483
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001484 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1485 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001486
Craig Topperf40110f2014-04-25 05:29:35 +00001487 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001488}
1489
Chad Rosiera00df492016-05-25 16:22:14 +00001490/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1491/// insert the new intrinsic and return it.
1492Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1494
1495 // Look through zero extends.
1496 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1497 Op0 = Ext->getOperand(0);
1498
1499 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1500 Op1 = Ext->getOperand(0);
1501
1502 // (A | B) | C and A | (B | C) -> bswap if possible.
1503 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1504 match(Op1, m_Or(m_Value(), m_Value()));
1505
1506 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1507 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1508 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1509
1510 // (A & B) | (C & D) -> bswap if possible.
1511 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1512 match(Op1, m_And(m_Value(), m_Value()));
1513
1514 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1515 return nullptr;
1516
James Molloyf01488e2016-01-15 09:20:19 +00001517 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001518 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001519 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001520 Instruction *LastInst = Insts.pop_back_val();
1521 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001522
James Molloyf01488e2016-01-15 09:20:19 +00001523 for (auto *Inst : Insts)
1524 Worklist.Add(Inst);
1525 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001526}
1527
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001528/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1529static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1530 unsigned NumElts = C1->getType()->getVectorNumElements();
1531 for (unsigned i = 0; i != NumElts; ++i) {
1532 Constant *EltC1 = C1->getAggregateElement(i);
1533 Constant *EltC2 = C2->getAggregateElement(i);
1534 if (!EltC1 || !EltC2)
1535 return false;
1536
1537 // One element must be all ones, and the other must be all zeros.
1538 // FIXME: Allow undef elements.
1539 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1540 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1541 return false;
1542 }
1543 return true;
1544}
1545
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001546/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1547/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1548/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001549static Value *getSelectCondition(Value *A, Value *B,
1550 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001551 // If these are scalars or vectors of i1, A can be used directly.
1552 Type *Ty = A->getType();
1553 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1554 return A;
1555
1556 // If A and B are sign-extended, look through the sexts to find the booleans.
1557 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001558 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001559 if (match(A, m_SExt(m_Value(Cond))) &&
1560 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001561 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1562 NotB = peekThroughBitcast(NotB, true);
1563 if (match(NotB, m_SExt(m_Specific(Cond))))
1564 return Cond;
1565 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001566
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001567 // All scalar (and most vector) possibilities should be handled now.
1568 // Try more matches that only apply to non-splat constant vectors.
1569 if (!Ty->isVectorTy())
1570 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001571
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001572 // If both operands are constants, see if the constants are inverse bitmasks.
1573 Constant *AC, *BC;
1574 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1575 areInverseVectorBitmasks(AC, BC))
1576 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1577
1578 // If both operands are xor'd with constants using the same sexted boolean
1579 // operand, see if the constants are inverse bitmasks.
1580 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1581 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1582 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1583 areInverseVectorBitmasks(AC, BC)) {
1584 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1585 return Builder.CreateXor(Cond, AC);
1586 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001587 return nullptr;
1588}
1589
1590/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1591/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001592static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001593 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001594 // The potential condition of the select may be bitcasted. In that case, look
1595 // through its bitcast and the corresponding bitcast of the 'not' condition.
1596 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001597 A = peekThroughBitcast(A, true);
1598 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001599
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001600 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001601 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001602 // The bitcasts will either all exist or all not exist. The builder will
1603 // not create unnecessary casts if the types already match.
1604 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1605 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1606 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1607 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001608 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001609
Craig Topperf40110f2014-04-25 05:29:35 +00001610 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001611}
1612
Sanjay Patel18549272015-09-08 18:24:36 +00001613/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001614Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001615 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001616 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1617 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001618 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1619 return V;
1620
1621 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1622
Sanjay Patel519a87a2017-04-05 17:38:34 +00001623 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1624 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001625
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001626 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1627 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1628 // The original condition actually refers to the following two ranges:
1629 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1630 // We can fold these two ranges if:
1631 // 1) C1 and C2 is unsigned greater than C3.
1632 // 2) The two ranges are separated.
1633 // 3) C1 ^ C2 is one-bit mask.
1634 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1635 // This implies all values in the two ranges differ by exactly one bit.
1636
Sanjay Patel519a87a2017-04-05 17:38:34 +00001637 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1638 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1639 LHSC->getType() == RHSC->getType() &&
1640 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001641
1642 Value *LAdd = LHS->getOperand(0);
1643 Value *RAdd = RHS->getOperand(0);
1644
1645 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001646 ConstantInt *LAddC, *RAddC;
1647 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1648 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1649 LAddC->getValue().ugt(LHSC->getValue()) &&
1650 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001651
Sanjay Patel519a87a2017-04-05 17:38:34 +00001652 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1653 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1654 ConstantInt *MaxAddC = nullptr;
1655 if (LAddC->getValue().ult(RAddC->getValue()))
1656 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001657 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001658 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001659
Sanjay Patel519a87a2017-04-05 17:38:34 +00001660 APInt RRangeLow = -RAddC->getValue();
1661 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1662 APInt LRangeLow = -LAddC->getValue();
1663 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001664 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1665 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1666 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1667 : RRangeLow - LRangeLow;
1668
1669 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001670 RangeDiff.ugt(LHSC->getValue())) {
1671 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001672
Sanjay Patel519a87a2017-04-05 17:38:34 +00001673 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1674 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1675 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001676 }
1677 }
1678 }
1679 }
1680
Chris Lattner0a8191e2010-01-05 07:50:36 +00001681 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001682 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001683 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1684 LHS->getOperand(1) == RHS->getOperand(0))
1685 LHS->swapOperands();
1686 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1687 LHS->getOperand(1) == RHS->getOperand(1)) {
1688 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1689 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1690 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001691 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001692 }
1693 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001694
1695 // handle (roughly):
1696 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001697 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001698 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001699
Sanjay Patele4159d22017-04-10 19:38:36 +00001700 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001701 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1702 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1703 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001704 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001705 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001706 B = LHS0;
1707 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1708 A = RHS0;
1709 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001710 A = RHS->getOperand(1);
1711 }
1712 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1713 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001714 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001715 B = RHS0;
1716 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1717 A = LHS0;
1718 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001719 A = LHS->getOperand(1);
1720 }
1721 if (A && B)
1722 return Builder->CreateICmp(
1723 ICmpInst::ICMP_UGE,
1724 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1725 }
1726
Erik Ecksteind1817522014-12-03 10:39:15 +00001727 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1728 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1729 return V;
1730
1731 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1732 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1733 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001734
Sanjay Patelef9f5862017-04-15 17:55:06 +00001735 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1736 return V;
1737
David Majnemerc2a990b2013-07-05 00:31:17 +00001738 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001739 if (!LHSC || !RHSC)
1740 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001741
Sanjay Patel519a87a2017-04-05 17:38:34 +00001742 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001743 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001744 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001745 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001746 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001747 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001748 }
1749
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001750 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001751 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001752 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1753 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001754 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001755 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001756 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001757 }
1758
Chris Lattner0a8191e2010-01-05 07:50:36 +00001759 // From here on, we only handle:
1760 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001761 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001762 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001763
Sanjay Patel519a87a2017-04-05 17:38:34 +00001764 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1765 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1766 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1767 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1768 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001769 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001770
Chris Lattner0a8191e2010-01-05 07:50:36 +00001771 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001772 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001773 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001774
Chris Lattner0a8191e2010-01-05 07:50:36 +00001775 // Ensure that the larger constant is on the RHS.
1776 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001777 if (CmpInst::isSigned(PredL) ||
1778 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001779 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001780 else
1781 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001782
Chris Lattner0a8191e2010-01-05 07:50:36 +00001783 if (ShouldSwap) {
1784 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001785 std::swap(LHSC, RHSC);
1786 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001787 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001788
Dan Gohman4a618822010-02-10 16:03:48 +00001789 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 // comparing a value against two constants and or'ing the result
1791 // together. Because of the above check, we know that we only have
1792 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1793 // icmp folding check above), that the two constants are not
1794 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001795 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001796
Sanjay Patel519a87a2017-04-05 17:38:34 +00001797 switch (PredL) {
1798 default:
1799 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001800 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001801 switch (PredR) {
1802 default:
1803 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001805 // Potential folds for this case should already be handled.
1806 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001807 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1808 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001810 }
1811 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001812 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001813 switch (PredR) {
1814 default:
1815 llvm_unreachable("Unknown integer condition code!");
1816 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001818 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001819 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001820 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1821 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001822 }
1823 break;
1824 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001825 switch (PredR) {
1826 default:
1827 llvm_unreachable("Unknown integer condition code!");
1828 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001830 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001831 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001832 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001833 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834 }
1835 break;
1836 }
Craig Topperf40110f2014-04-25 05:29:35 +00001837 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838}
1839
Sanjay Patel18549272015-09-08 18:24:36 +00001840/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1841/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001842Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001843 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1844 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1845 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1846
1847 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1848 // Swap RHS operands to match LHS.
1849 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1850 std::swap(Op1LHS, Op1RHS);
1851 }
1852
1853 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1854 // This is a similar transformation to the one in FoldAndOfFCmps.
1855 //
1856 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1857 // bool(R & CC0) || bool(R & CC1)
1858 // = bool((R & CC0) | (R & CC1))
1859 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1860 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1861 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1862 Builder);
1863
Chris Lattner0a8191e2010-01-05 07:50:36 +00001864 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001865 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001866 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1867 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1868 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1869 // If either of the constants are nans, then the whole thing returns
1870 // true.
1871 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001872 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001873
Chris Lattner0a8191e2010-01-05 07:50:36 +00001874 // Otherwise, no need to compare the two constants, compare the
1875 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001876 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001878
Chris Lattner0a8191e2010-01-05 07:50:36 +00001879 // Handle vector zeros. This occurs because the canonical form of
1880 // "fcmp uno x,x" is "fcmp uno x, 0".
1881 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1882 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001883 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001884
Craig Topperf40110f2014-04-25 05:29:35 +00001885 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001886 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001887
Craig Topperf40110f2014-04-25 05:29:35 +00001888 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001889}
1890
Sanjay Patel18549272015-09-08 18:24:36 +00001891/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001892///
1893/// ((A | B) & C1) | (B & C2)
1894///
1895/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001896///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897/// (A & C1) | B
1898///
1899/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001900static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1901 Value *A, Value *B, Value *C,
1902 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001903 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001904 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001905
Craig Topperf40110f2014-04-25 05:29:35 +00001906 Value *V1 = nullptr;
1907 ConstantInt *CI2 = nullptr;
1908 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909
1910 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001911 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001912
1913 if (V1 == A || V1 == B) {
1914 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1915 return BinaryOperator::CreateOr(NewOp, V1);
1916 }
1917
Craig Topperf40110f2014-04-25 05:29:35 +00001918 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001919}
1920
David Majnemer5d1aeba2014-08-21 05:14:48 +00001921/// \brief This helper function folds:
1922///
Craig Toppera074c102017-06-21 18:57:00 +00001923/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001924///
1925/// into:
1926///
1927/// (A & C1) ^ B
1928///
1929/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001930static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1931 Value *A, Value *B, Value *C,
1932 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001933 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1934 if (!CI1)
1935 return nullptr;
1936
1937 Value *V1 = nullptr;
1938 ConstantInt *CI2 = nullptr;
1939 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1940 return nullptr;
1941
1942 APInt Xor = CI1->getValue() ^ CI2->getValue();
1943 if (!Xor.isAllOnesValue())
1944 return nullptr;
1945
1946 if (V1 == A || V1 == B) {
1947 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1948 return BinaryOperator::CreateXor(NewOp, V1);
1949 }
1950
1951 return nullptr;
1952}
1953
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001954// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1955// here. We should standardize that construct where it is needed or choose some
1956// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001957Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001958 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1960
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001961 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001962 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001963
Craig Toppera4205622017-06-09 03:21:29 +00001964 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001965 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001966
Craig Topper9d4171a2012-12-20 07:09:41 +00001967 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968 // purpose is to compute bits we don't care about.
1969 if (SimplifyDemandedInstructionBits(I))
1970 return &I;
1971
Sanjay Patele0c26e02017-04-23 22:00:02 +00001972 // Do this before using distributive laws to catch simple and/or/not patterns.
1973 if (Instruction *Xor = foldOrToXor(I, *Builder))
1974 return Xor;
1975
1976 // (A&B)|(A&C) -> A&(B|C) etc
1977 if (Value *V = SimplifyUsingDistributiveLaws(I))
1978 return replaceInstUsesWith(I, V);
1979
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001980 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001981 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001982
Craig Topper86173602017-04-04 20:26:25 +00001983 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001984 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1985 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001986
Chad Rosiere5819e22016-05-26 14:58:51 +00001987 // Given an OR instruction, check to see if this is a bswap.
1988 if (Instruction *BSwap = MatchBSwap(I))
1989 return BSwap;
1990
Craig Topperafa07c52017-04-09 06:12:41 +00001991 {
1992 Value *A;
1993 const APInt *C;
1994 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1995 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1996 MaskedValueIsZero(Op1, *C, 0, &I)) {
1997 Value *NOr = Builder->CreateOr(A, Op1);
1998 NOr->takeName(Op0);
1999 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002000 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002001 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002002
Craig Topperafa07c52017-04-09 06:12:41 +00002003 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2004 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2005 MaskedValueIsZero(Op0, *C, 0, &I)) {
2006 Value *NOr = Builder->CreateOr(A, Op0);
2007 NOr->takeName(Op0);
2008 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002009 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002010 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002011 }
2012
Craig Topperafa07c52017-04-09 06:12:41 +00002013 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002014
Suyog Sardad64faf62014-07-22 18:09:41 +00002015 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002016 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2017 return BinaryOperator::CreateOr(A, Op1);
2018 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2019 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002020
2021 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002022 // The NOT is guaranteed to be in the RHS by complexity ordering.
2023 if (match(Op1, m_Not(m_Value(A))) &&
2024 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2025 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002026
Chris Lattner0a8191e2010-01-05 07:50:36 +00002027 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002028 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002029 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2030 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002031 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002032 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2033 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002034 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002035 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002036 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002037 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002039 ((V1 == B &&
2040 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2041 (V2 == B &&
2042 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002043 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002044 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002045 // Or commutes, try both ways.
2046 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002047 ((V1 == A &&
2048 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2049 (V2 == A &&
2050 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002052 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002053
Chris Lattner95188692010-01-11 06:55:24 +00002054 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002055 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002056 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002057 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002058 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002059 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002060 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002061 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2062 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002063 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002064 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002065 }
2066 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002067
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002068 // Don't try to form a select if it's unlikely that we'll get rid of at
2069 // least one of the operands. A select is generally more expensive than the
2070 // 'or' that it is replacing.
2071 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2072 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2073 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2074 return replaceInstUsesWith(I, V);
2075 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2076 return replaceInstUsesWith(I, V);
2077 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2078 return replaceInstUsesWith(I, V);
2079 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2080 return replaceInstUsesWith(I, V);
2081 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2082 return replaceInstUsesWith(I, V);
2083 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2084 return replaceInstUsesWith(I, V);
2085 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2086 return replaceInstUsesWith(I, V);
2087 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2088 return replaceInstUsesWith(I, V);
2089 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002090
Benjamin Kramer11743242010-07-12 13:34:22 +00002091 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002092 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2093 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2094 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002095 }
2096 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002097 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2098 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2099 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002100 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002101 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002102 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2103 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2104 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002105 }
2106 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002107 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2108 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2109 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002110 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002111 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002112
David Majnemer42af3602014-07-30 21:26:37 +00002113 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2114 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2115 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002116 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002117
2118 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2119 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2120 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002121 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002122
David Majnemerf1eda232014-08-14 06:41:38 +00002123 // ((B | C) & A) | B -> B | (A & C)
2124 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2125 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2126
Sanjay Patel7caaa792017-05-09 20:05:05 +00002127 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002128 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002129
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002130 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002131 bool SwappedForXor = false;
2132 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002133 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002134 SwappedForXor = true;
2135 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002136
2137 // A | ( A ^ B) -> A | B
2138 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002139 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002140 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2141 if (Op0 == A || Op0 == B)
2142 return BinaryOperator::CreateOr(A, B);
2143
Chad Rosier7813dce2012-04-26 23:29:14 +00002144 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2145 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2146 return BinaryOperator::CreateOr(A, B);
2147
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002148 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2149 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2150 return BinaryOperator::CreateOr(Not, Op0);
2151 }
2152 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2153 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2154 return BinaryOperator::CreateOr(Not, Op0);
2155 }
2156 }
2157
2158 // A | ~(A | B) -> A | ~B
2159 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002160 if (match(Op1, m_Not(m_Value(A))))
2161 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002162 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2163 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2164 B->getOpcode() == Instruction::Xor)) {
2165 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2166 B->getOperand(0);
2167 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2168 return BinaryOperator::CreateOr(Not, Op0);
2169 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002170
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002171 // (A & B) | (~A ^ B) -> (~A ^ B)
2172 // (A & B) | (B ^ ~A) -> (~A ^ B)
2173 // (B & A) | (~A ^ B) -> (~A ^ B)
2174 // (B & A) | (B ^ ~A) -> (~A ^ B)
2175 // The match order is important: match the xor first because the 'not'
2176 // operation defines 'A'. We do not need to match the xor as Op0 because the
2177 // xor was canonicalized to Op1 above.
2178 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2179 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002180 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2181
Eli Friedmane06535b2012-03-16 00:52:42 +00002182 if (SwappedForXor)
2183 std::swap(Op0, Op1);
2184
David Majnemer3d6f80b2014-11-28 19:58:29 +00002185 {
2186 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2187 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2188 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002189 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002190 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002191
David Majnemer3d6f80b2014-11-28 19:58:29 +00002192 // TODO: Make this recursive; it's a little tricky because an arbitrary
2193 // number of 'or' instructions might have to be created.
2194 Value *X, *Y;
2195 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2196 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002197 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002198 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002199 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002200 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002201 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002202 }
2203 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2204 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002205 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002206 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002207 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002208 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002209 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002210 }
2211 }
2212
Chris Lattner4e8137d2010-02-11 06:26:33 +00002213 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2214 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2215 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002216 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002217 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002218
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002219 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2220 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002221
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002222 // 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 +00002223 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002224 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002225 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002226 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002227 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002228 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2229
Owen Andersonc237a842010-09-13 17:59:27 +00002230 // Note: If we've gotten to the point of visiting the outer OR, then the
2231 // inner one couldn't be simplified. If it was a constant, then it won't
2232 // be simplified by a later pass either, so we try swapping the inner/outer
2233 // ORs in the hopes that we'll be able to simplify it this way.
2234 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002235 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002236 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2237 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2238 Value *Inner = Builder->CreateOr(A, Op1);
2239 Inner->takeName(Op0);
2240 return BinaryOperator::CreateOr(Inner, C1);
2241 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002242
Bill Wendling23242092013-02-16 23:41:36 +00002243 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2244 // Since this OR statement hasn't been optimized further yet, we hope
2245 // that this transformation will allow the new ORs to be optimized.
2246 {
Craig Topperf40110f2014-04-25 05:29:35 +00002247 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002248 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2249 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2250 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2251 Value *orTrue = Builder->CreateOr(A, C);
2252 Value *orFalse = Builder->CreateOr(B, D);
2253 return SelectInst::Create(X, orTrue, orFalse);
2254 }
2255 }
2256
Craig Topperf40110f2014-04-25 05:29:35 +00002257 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002258}
2259
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002260/// A ^ B can be specified using other logic ops in a variety of patterns. We
2261/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002262static Instruction *foldXorToXor(BinaryOperator &I,
2263 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002264 assert(I.getOpcode() == Instruction::Xor);
2265 Value *Op0 = I.getOperand(0);
2266 Value *Op1 = I.getOperand(1);
2267 Value *A, *B;
2268
2269 // There are 4 commuted variants for each of the basic patterns.
2270
2271 // (A & B) ^ (A | B) -> A ^ B
2272 // (A & B) ^ (B | A) -> A ^ B
2273 // (A | B) ^ (A & B) -> A ^ B
2274 // (A | B) ^ (B & A) -> A ^ B
2275 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2276 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2277 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2278 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2279 I.setOperand(0, A);
2280 I.setOperand(1, B);
2281 return &I;
2282 }
2283
2284 // (A | ~B) ^ (~A | B) -> A ^ B
2285 // (~B | A) ^ (~A | B) -> A ^ B
2286 // (~A | B) ^ (A | ~B) -> A ^ B
2287 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002288 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2289 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2290 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2291 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002292 I.setOperand(0, A);
2293 I.setOperand(1, B);
2294 return &I;
2295 }
2296
2297 // (A & ~B) ^ (~A & B) -> A ^ B
2298 // (~B & A) ^ (~A & B) -> A ^ B
2299 // (~A & B) ^ (A & ~B) -> A ^ B
2300 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002301 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2302 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2303 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2304 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002305 I.setOperand(0, A);
2306 I.setOperand(1, B);
2307 return &I;
2308 }
2309
Craig Topperf60ab472017-07-02 01:15:51 +00002310 // For the remaining cases we need to get rid of one of the operands.
2311 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2312 return nullptr;
2313
2314 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2315 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2316 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2317 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2318 // Complexity sorting ensures the not will be on the right side.
2319 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2320 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2321 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2322 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2323 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2324
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002325 return nullptr;
2326}
2327
Sanjay Patel5e456b92017-05-18 20:53:16 +00002328Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2329 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2330 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2331 LHS->getOperand(1) == RHS->getOperand(0))
2332 LHS->swapOperands();
2333 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2334 LHS->getOperand(1) == RHS->getOperand(1)) {
2335 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2336 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2337 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2338 bool isSigned = LHS->isSigned() || RHS->isSigned();
2339 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2340 }
2341 }
2342
Sanjay Pateladca8252017-06-20 12:40:55 +00002343 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2344 // into those logic ops. That is, try to turn this into an and-of-icmps
2345 // because we have many folds for that pattern.
2346 //
2347 // This is based on a truth table definition of xor:
2348 // X ^ Y --> (X | Y) & !(X & Y)
2349 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2350 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2351 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2352 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2353 // TODO: Independently handle cases where the 'and' side is a constant.
2354 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2355 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2356 RHS->setPredicate(RHS->getInversePredicate());
2357 return Builder->CreateAnd(LHS, RHS);
2358 }
2359 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002360 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002361 LHS->setPredicate(LHS->getInversePredicate());
2362 return Builder->CreateAnd(LHS, RHS);
2363 }
2364 }
2365 }
2366
Sanjay Patel5e456b92017-05-18 20:53:16 +00002367 return nullptr;
2368}
2369
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002370// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2371// here. We should standardize that construct where it is needed or choose some
2372// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002373Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002374 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2376
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002377 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002378 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002379
Craig Toppera4205622017-06-09 03:21:29 +00002380 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002381 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002382
Craig Topperf60ab472017-07-02 01:15:51 +00002383 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002384 return NewXor;
2385
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002386 // (A&B)^(A&C) -> A&(B^C) etc
2387 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002389
Craig Topper9d4171a2012-12-20 07:09:41 +00002390 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002391 // purpose is to compute bits we don't care about.
2392 if (SimplifyDemandedInstructionBits(I))
2393 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002394
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002395 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002396 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002397
Sanjay Patel6381db12017-05-02 15:31:40 +00002398 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2399 Value *X, *Y;
2400
2401 // We must eliminate the and/or (one-use) for these transforms to not increase
2402 // the instruction count.
2403 // ~(~X & Y) --> (X | ~Y)
2404 // ~(Y & ~X) --> (X | ~Y)
2405 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2406 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2407 return BinaryOperator::CreateOr(X, NotY);
2408 }
2409 // ~(~X | Y) --> (X & ~Y)
2410 // ~(Y | ~X) --> (X & ~Y)
2411 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2412 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2413 return BinaryOperator::CreateAnd(X, NotY);
2414 }
2415
Sanjay Patel3b863f82017-04-22 18:05:35 +00002416 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002417 BinaryOperator *NotVal;
2418 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2419 if (NotVal->getOpcode() == Instruction::And ||
2420 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002421 // Apply DeMorgan's Law when inverts are free:
2422 // ~(X & Y) --> (~X | ~Y)
2423 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002424 if (IsFreeToInvert(NotVal->getOperand(0),
2425 NotVal->getOperand(0)->hasOneUse()) &&
2426 IsFreeToInvert(NotVal->getOperand(1),
2427 NotVal->getOperand(1)->hasOneUse())) {
2428 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2429 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2430 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002431 return BinaryOperator::CreateOr(NotX, NotY);
2432 return BinaryOperator::CreateAnd(NotX, NotY);
2433 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002434 }
2435
2436 // ~(~X >>s Y) --> (X >>s Y)
2437 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2438 return BinaryOperator::CreateAShr(X, Y);
2439
2440 // If we are inverting a right-shifted constant, we may be able to eliminate
2441 // the 'not' by inverting the constant and using the opposite shift type.
2442 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2443 // but we must check that in case that transform has not fired yet.
2444 const APInt *C;
2445 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2446 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2447 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2448 return BinaryOperator::CreateLShr(NotC, Y);
2449 }
2450
2451 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2452 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2453 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2454 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002455 }
2456 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002457
Craig Topper798a19a2017-06-29 00:07:08 +00002458 // not (cmp A, B) = !cmp A, B
Sanjay Patel33439f92017-04-12 15:11:33 +00002459 ICmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002460 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002461 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2462 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002463 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002464
Craig Topper9d1821b2017-04-09 06:12:31 +00002465 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002466 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2467 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2468 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2469 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2470 Instruction::CastOps Opcode = Op0C->getOpcode();
2471 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002472 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002473 Op0C->getDestTy()))) {
2474 CI->setPredicate(CI->getInversePredicate());
2475 return CastInst::Create(Opcode, CI, Op0C->getType());
2476 }
2477 }
2478 }
2479 }
2480
2481 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2482 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002483 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002484 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2485 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002486 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2487 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002488 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002489
Chris Lattner0a8191e2010-01-05 07:50:36 +00002490 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2491 if (Op0I->getOpcode() == Instruction::Add) {
2492 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002493 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002494 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002495 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2496 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002497 } else if (RHSC->getValue().isSignMask()) {
2498 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002499 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002500 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2501
2502 }
2503 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002504 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002505 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2506 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002507 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002508 // Anything in both C1 and C2 is known to be zero, remove it from
2509 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002510 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002511 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002512 ConstantExpr::getNot(CommonBits));
2513 Worklist.Add(Op0I);
2514 I.setOperand(0, Op0I->getOperand(0));
2515 I.setOperand(1, NewRHS);
2516 return &I;
2517 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002518 } else if (Op0I->getOpcode() == Instruction::LShr) {
2519 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2520 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002521 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002522 ConstantInt *C1;
2523 if (Op0I->hasOneUse() &&
2524 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2525 E1->getOpcode() == Instruction::Xor &&
2526 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2527 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002528 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002529 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2530 FoldConst ^= C3->getValue();
2531 // Prepare the two operands.
2532 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2533 Opnd0->takeName(Op0I);
2534 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2535 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2536
2537 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2538 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002539 }
2540 }
2541 }
Craig Topper86173602017-04-04 20:26:25 +00002542 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002543
Craig Topper86173602017-04-04 20:26:25 +00002544 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002545 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2546 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002547
Craig Topper76394602017-04-10 06:53:23 +00002548 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002549 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002550 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002551 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002552 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002553 std::swap(A, B);
2554 }
2555 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002556 I.swapOperands(); // Simplified below.
2557 std::swap(Op0, Op1);
2558 }
Craig Topper76394602017-04-10 06:53:23 +00002559 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002560 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002561 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002562 std::swap(A, B);
2563 }
2564 if (B == Op0) { // A^(B&A) -> (B&A)^A
2565 I.swapOperands(); // Simplified below.
2566 std::swap(Op0, Op1);
2567 }
2568 }
2569 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002570
Craig Topper76394602017-04-10 06:53:23 +00002571 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002572 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002573 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002574 if (A == Op1) // (B|A)^B == (A|B)^B
2575 std::swap(A, B);
2576 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002577 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002578 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002579 if (A == Op1) // (A&B)^A -> (B&A)^A
2580 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002581 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002582 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002583 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002584 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002585 }
2586 }
2587 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002588
Craig Topper76394602017-04-10 06:53:23 +00002589 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002590 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002591 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002592 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2593 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002594 if (D == A)
2595 return BinaryOperator::CreateXor(
2596 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2597 if (D == B)
2598 return BinaryOperator::CreateXor(
2599 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002600 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002601 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002602 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2603 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002604 if (D == A)
2605 return BinaryOperator::CreateXor(
2606 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2607 if (D == B)
2608 return BinaryOperator::CreateXor(
2609 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002610 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002611 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002612 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002613 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002614 return BinaryOperator::CreateOr(A, B);
2615 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002616 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002617 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002618 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002619 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002620
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002621 // (A & ~B) ^ ~A -> ~(A & B)
2622 // (~B & A) ^ ~A -> ~(A & B)
2623 Value *A, *B;
2624 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002625 match(Op1, m_Not(m_Specific(A))))
2626 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2627
Sanjay Patel5e456b92017-05-18 20:53:16 +00002628 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2629 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2630 if (Value *V = foldXorOfICmps(LHS, RHS))
2631 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002632
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002633 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2634 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002635
Craig Topperf40110f2014-04-25 05:29:35 +00002636 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002637}