blob: 20c75a3ec0aef0db46a11515e1631cb8ad0d59e8 [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
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
Craig Topper95e41422017-07-06 16:24:23 +000083static Value *SimplifyBSwap(BinaryOperator &I,
84 InstCombiner::BuilderTy *Builder) {
Craig Topperc6948c22017-07-03 05:54:11 +000085 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86
Craig Topper22795de2017-07-06 16:24:21 +000087 Value *OldLHS = I.getOperand(0);
88 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000089
Craig Topper766ce6e2017-07-03 05:54:15 +000090 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000091 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000092 return nullptr;
93
Craig Topper766ce6e2017-07-03 05:54:15 +000094 Value *NewRHS;
95 const APInt *C;
96
Craig Topper22795de2017-07-06 16:24:21 +000097 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000098 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000099 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
100 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000102 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000103 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000104 if (!OldLHS->hasOneUse())
105 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000106 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
107 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000108 return nullptr;
109
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000110 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000111 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
112 I.getType());
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000113 return Builder->CreateCall(F, BinOp);
114}
115
Sanjay Patel18549272015-09-08 18:24:36 +0000116/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000117/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
118Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000119 ConstantInt *OpRHS,
120 ConstantInt *AndRHS,
121 BinaryOperator &TheAnd) {
122 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000123 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000124 if (!Op->isShift())
125 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
126
127 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000128 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000129 case Instruction::Xor:
130 if (Op->hasOneUse()) {
131 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
132 Value *And = Builder->CreateAnd(X, AndRHS);
133 And->takeName(Op);
134 return BinaryOperator::CreateXor(And, Together);
135 }
136 break;
137 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000138 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000139 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
140 if (TogetherCI && !TogetherCI->isZero()){
141 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
142 // NOTE: This reduces the number of bits set in the & mask, which
143 // can expose opportunities for store narrowing.
144 Together = ConstantExpr::getXor(AndRHS, Together);
145 Value *And = Builder->CreateAnd(X, Together);
146 And->takeName(Op);
147 return BinaryOperator::CreateOr(And, OpRHS);
148 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000149 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000150
Chris Lattner0a8191e2010-01-05 07:50:36 +0000151 break;
152 case Instruction::Add:
153 if (Op->hasOneUse()) {
154 // Adding a one to a single bit bit-field should be turned into an XOR
155 // of the bit. First thing to check is to see if this AND is with a
156 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000157 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000158
159 // If there is only one bit set.
160 if (AndRHSV.isPowerOf2()) {
161 // Ok, at this point, we know that we are masking the result of the
162 // ADD down to exactly one bit. If the constant we are adding has
163 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000164 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000165
166 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000167 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000168 // If not, the only thing that can effect the output of the AND is
169 // the bit specified by AndRHSV. If that bit is set, the effect of
170 // the XOR is to toggle the bit. If it is clear, then the ADD has
171 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000172 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000173 TheAnd.setOperand(0, X);
174 return &TheAnd;
175 } else {
176 // Pull the XOR out of the AND.
177 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
178 NewAnd->takeName(Op);
179 return BinaryOperator::CreateXor(NewAnd, AndRHS);
180 }
181 }
182 }
183 }
184 break;
185
186 case Instruction::Shl: {
187 // We know that the AND will not produce any of the bits shifted in, so if
188 // the anded constant includes them, clear them now!
189 //
190 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
191 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
192 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000193 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000194
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000195 if (CI->getValue() == ShlMask)
196 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000197 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000198
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000199 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000200 TheAnd.setOperand(1, CI);
201 return &TheAnd;
202 }
203 break;
204 }
205 case Instruction::LShr: {
206 // We know that the AND will not produce any of the bits shifted in, so if
207 // the anded constant includes them, clear them now! This only applies to
208 // unsigned shifts, because a signed shr may bring in set bits!
209 //
210 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
211 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
212 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000213 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000214
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000215 if (CI->getValue() == ShrMask)
216 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000217 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000218
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000219 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000220 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
221 return &TheAnd;
222 }
223 break;
224 }
225 case Instruction::AShr:
226 // Signed shr.
227 // See if this is shifting in some sign extension, then masking it out
228 // with an and.
229 if (Op->hasOneUse()) {
230 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
231 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
232 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000233 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000234 if (C == AndRHS) { // Masking out bits shifted in.
235 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
236 // Make the argument unsigned.
237 Value *ShVal = Op->getOperand(0);
238 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
239 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
240 }
241 }
242 break;
243 }
Craig Topperf40110f2014-04-25 05:29:35 +0000244 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000245}
246
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000247/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000248/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
249/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000250Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000251 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000252 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000253 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000254
Sanjay Patel85d79742016-08-31 19:49:56 +0000255 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000256 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000257 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000258
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000259 // V >= Min && V < Hi --> V < Hi
260 // V < Min || V >= Hi --> V >= Hi
261 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000262 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000263 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000264 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000265 }
266
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000267 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
268 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000269 Value *VMinusLo =
270 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
271 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000272 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000273}
274
Sanjay Patel77bf6222017-04-03 16:53:12 +0000275/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
276/// that can be simplified.
277/// One of A and B is considered the mask. The other is the value. This is
278/// described as the "AMask" or "BMask" part of the enum. If the enum contains
279/// only "Mask", then both A and B can be considered masks. If A is the mask,
280/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
281/// If both A and C are constants, this proof is also easy.
282/// For the following explanations, we assume that A is the mask.
283///
284/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
285/// bits of A are set in B.
286/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
287///
288/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
289/// bits of A are cleared in B.
290/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
291///
292/// "Mixed" declares that (A & B) == C and C might or might not contain any
293/// number of one bits and zero bits.
294/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
295///
296/// "Not" means that in above descriptions "==" should be replaced by "!=".
297/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
298///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000299/// If the mask A contains a single bit, then the following is equivalent:
300/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
301/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
302enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000303 AMask_AllOnes = 1,
304 AMask_NotAllOnes = 2,
305 BMask_AllOnes = 4,
306 BMask_NotAllOnes = 8,
307 Mask_AllZeros = 16,
308 Mask_NotAllZeros = 32,
309 AMask_Mixed = 64,
310 AMask_NotMixed = 128,
311 BMask_Mixed = 256,
312 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000313};
314
Sanjay Patel77bf6222017-04-03 16:53:12 +0000315/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
316/// satisfies.
317static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
318 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000319 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
320 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
321 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000322 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
323 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
324 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
325 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000326 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000327 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000328 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
329 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
330 if (IsAPow2)
331 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
332 : (AMask_AllOnes | AMask_Mixed));
333 if (IsBPow2)
334 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
335 : (BMask_AllOnes | BMask_Mixed));
336 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000337 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000338
Owen Anderson3fe002d2010-09-08 22:16:17 +0000339 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000340 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
341 : (AMask_NotAllOnes | AMask_NotMixed));
342 if (IsAPow2)
343 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
344 : (Mask_AllZeros | AMask_Mixed));
345 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
346 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000347 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348
Craig Topperae48cb22012-12-20 07:15:54 +0000349 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000350 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
351 : (BMask_NotAllOnes | BMask_NotMixed));
352 if (IsBPow2)
353 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
354 : (Mask_AllZeros | BMask_Mixed));
355 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
356 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000357 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000358
359 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000360}
361
Tim Northoverc0756c42013-09-04 11:57:13 +0000362/// Convert an analysis of a masked ICmp into its equivalent if all boolean
363/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
364/// is adjacent to the corresponding normal flag (recording ==), this just
365/// involves swapping those bits over.
366static unsigned conjugateICmpMask(unsigned Mask) {
367 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000368 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
369 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000370 << 1;
371
Sanjay Patel77bf6222017-04-03 16:53:12 +0000372 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
373 AMask_NotMixed | BMask_NotMixed))
374 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000375
376 return NewMask;
377}
378
Sanjay Patel77bf6222017-04-03 16:53:12 +0000379/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
380/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
381/// RHS satisfy.
382static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
383 Value *&D, Value *&E, ICmpInst *LHS,
384 ICmpInst *RHS,
385 ICmpInst::Predicate &PredL,
386 ICmpInst::Predicate &PredR) {
387 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
388 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000389 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000390 if (LHS->getOperand(0)->getType()->isVectorTy())
391 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000392
393 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000394 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000395 // and L11 & L12 == L21 & L22. The same goes for RHS.
396 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000397 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000398 // above.
399 Value *L1 = LHS->getOperand(0);
400 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000401 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000402 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000403 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000404 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000405 } else {
406 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000407 if (!L1->getType()->isIntegerTy()) {
408 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000409 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000410 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
411 // Any icmp can be viewed as being trivially masked; if it allows us to
412 // remove one, it's worth it.
413 L11 = L1;
414 L12 = Constant::getAllOnesValue(L1->getType());
415 }
416
417 if (!L2->getType()->isIntegerTy()) {
418 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000419 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000420 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
421 L21 = L2;
422 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000423 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000425
426 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000427 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000428 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429
430 Value *R1 = RHS->getOperand(0);
431 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000432 Value *R11, *R12;
433 bool Ok = false;
434 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000435 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000436 A = R11;
437 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000438 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000439 A = R12;
440 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000441 } else {
442 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000443 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000444 E = R2;
445 R1 = nullptr;
446 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000447 } else if (R1->getType()->isIntegerTy()) {
448 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
449 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000450 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000451 R11 = R1;
452 R12 = Constant::getAllOnesValue(R1->getType());
453 }
454
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000455 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000456 A = R11;
457 D = R12;
458 E = R2;
459 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000460 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000461 A = R12;
462 D = R11;
463 E = R2;
464 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000465 }
466 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000467
468 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000469 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000470 return 0;
471
Chad Rosier58919cc2016-05-09 21:37:43 +0000472 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000473 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000474 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
475 R11 = R2;
476 R12 = Constant::getAllOnesValue(R2->getType());
477 }
478
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000479 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000480 A = R11;
481 D = R12;
482 E = R1;
483 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000484 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000485 A = R12;
486 D = R11;
487 E = R1;
488 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000489 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000490 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000491 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000492 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000493 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000494 return 0;
495
496 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000497 B = L12;
498 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000499 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000500 B = L11;
501 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000502 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000503 B = L22;
504 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000505 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000506 B = L21;
507 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000508 }
509
Sanjay Patel77bf6222017-04-03 16:53:12 +0000510 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
511 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000512 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000513}
Sanjay Patel18549272015-09-08 18:24:36 +0000514
515/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
516/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000517static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
518 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000519 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000520 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
521 unsigned Mask =
522 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
523 if (Mask == 0)
524 return nullptr;
525
526 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
527 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000528
Tim Northoverc0756c42013-09-04 11:57:13 +0000529 // In full generality:
530 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
531 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
532 //
533 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
534 // equivalent to (icmp (A & X) !Op Y).
535 //
536 // Therefore, we can pretend for the rest of this function that we're dealing
537 // with the conjunction, provided we flip the sense of any comparisons (both
538 // input and output).
539
540 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000541 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000542 if (!IsAnd) {
543 // Convert the masking analysis into its equivalent with negated
544 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000545 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000546 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000547
Sanjay Patel77bf6222017-04-03 16:53:12 +0000548 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000549 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000550 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000551 Value *NewOr = Builder->CreateOr(B, D);
552 Value *NewAnd = Builder->CreateAnd(A, NewOr);
553 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000554 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000555 // with B and D, having a single bit set.
556 Value *Zero = Constant::getNullValue(A->getType());
557 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000558 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000559 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000560 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000561 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000562 Value *NewOr = Builder->CreateOr(B, D);
563 Value *NewAnd = Builder->CreateAnd(A, NewOr);
564 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000565 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000566 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000567 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000568 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000569 Value *NewAnd1 = Builder->CreateAnd(B, D);
570 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
571 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000572 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000573
574 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000575 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000576 // easy cases for now" decision.
577 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000578 if (!BCst)
579 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000580 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000581 if (!DCst)
582 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000583
Sanjay Patel77bf6222017-04-03 16:53:12 +0000584 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000585 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
586 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
587 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
588 // Only valid if one of the masks is a superset of the other (check "B&D" is
589 // the same as either B or D).
590 APInt NewMask = BCst->getValue() & DCst->getValue();
591
592 if (NewMask == BCst->getValue())
593 return LHS;
594 else if (NewMask == DCst->getValue())
595 return RHS;
596 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000597
598 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000599 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
600 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
601 // Only valid if one of the masks is a superset of the other (check "B|D" is
602 // the same as either B or D).
603 APInt NewMask = BCst->getValue() | DCst->getValue();
604
605 if (NewMask == BCst->getValue())
606 return LHS;
607 else if (NewMask == DCst->getValue())
608 return RHS;
609 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000610
611 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000612 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000613 // We already know that B & C == C && D & E == E.
614 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
615 // C and E, which are shared by both the mask B and the mask D, don't
616 // contradict, then we can transform to
617 // -> (icmp eq (A & (B|D)), (C|E))
618 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000619 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000620 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000621 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000622 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000623 if (!CCst)
624 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000625 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000626 if (!ECst)
627 return nullptr;
628 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000629 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000630 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000631 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000632
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000633 // If there is a conflict, we should actually return a false for the
634 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000635 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000636 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000637 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000638
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000639 Value *NewOr1 = Builder->CreateOr(B, D);
640 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
641 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
642 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000643 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000644
Craig Topperf40110f2014-04-25 05:29:35 +0000645 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000646}
647
Erik Ecksteind1817522014-12-03 10:39:15 +0000648/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
649/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
650/// If \p Inverted is true then the check is for the inverted range, e.g.
651/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
652Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
653 bool Inverted) {
654 // Check the lower range comparison, e.g. x >= 0
655 // InstCombine already ensured that if there is a constant it's on the RHS.
656 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
657 if (!RangeStart)
658 return nullptr;
659
660 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
661 Cmp0->getPredicate());
662
663 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
664 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
665 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
666 return nullptr;
667
668 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
669 Cmp1->getPredicate());
670
671 Value *Input = Cmp0->getOperand(0);
672 Value *RangeEnd;
673 if (Cmp1->getOperand(0) == Input) {
674 // For the upper range compare we have: icmp x, n
675 RangeEnd = Cmp1->getOperand(1);
676 } else if (Cmp1->getOperand(1) == Input) {
677 // For the upper range compare we have: icmp n, x
678 RangeEnd = Cmp1->getOperand(0);
679 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
680 } else {
681 return nullptr;
682 }
683
684 // Check the upper range comparison, e.g. x < n
685 ICmpInst::Predicate NewPred;
686 switch (Pred1) {
687 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
688 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
689 default: return nullptr;
690 }
691
692 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000693 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
694 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000695 return nullptr;
696
697 if (Inverted)
698 NewPred = ICmpInst::getInversePredicate(NewPred);
699
700 return Builder->CreateICmp(NewPred, Input, RangeEnd);
701}
702
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000703static Value *
704foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
705 bool JoinedByAnd,
706 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000707 Value *X = LHS->getOperand(0);
708 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000709 return nullptr;
710
Sanjay Patelef9f5862017-04-15 17:55:06 +0000711 const APInt *C1, *C2;
712 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
713 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000714 return nullptr;
715
716 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
717 ICmpInst::Predicate Pred = LHS->getPredicate();
718 if (Pred != RHS->getPredicate())
719 return nullptr;
720 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
721 return nullptr;
722 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
723 return nullptr;
724
725 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000726 if (C1->ugt(*C2))
727 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000728
Sanjay Patelef9f5862017-04-15 17:55:06 +0000729 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000730 if (Xor.isPowerOf2()) {
731 // If LHSC and RHSC differ by only one bit, then set that bit in X and
732 // compare against the larger constant:
733 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
734 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
735 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
736 // 'and' because that may lead to smaller codegen from a smaller constant.
737 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000738 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000739 }
740
741 // Special case: get the ordering right when the values wrap around zero.
742 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000743 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000744 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000745
Sanjay Patelef9f5862017-04-15 17:55:06 +0000746 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000747 // (X == 13 || X == 14) --> X - 13 <=u 1
748 // (X != 13 && X != 14) --> X - 13 >u 1
749 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000750 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000751 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
752 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
753 }
754
755 return nullptr;
756}
757
Craig Topperda6ea0d2017-06-16 05:10:37 +0000758// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
759// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
760Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
761 bool JoinedByAnd,
762 Instruction &CxtI) {
763 ICmpInst::Predicate Pred = LHS->getPredicate();
764 if (Pred != RHS->getPredicate())
765 return nullptr;
766 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
767 return nullptr;
768 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
769 return nullptr;
770
771 // TODO support vector splats
772 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
773 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
774 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
775 return nullptr;
776
777 Value *A, *B, *C, *D;
778 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
779 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
780 if (A == D || B == D)
781 std::swap(C, D);
782 if (B == C)
783 std::swap(A, B);
784
785 if (A == C &&
786 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
787 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
788 Value *Mask = Builder->CreateOr(B, D);
789 Value *Masked = Builder->CreateAnd(A, Mask);
790 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
791 return Builder->CreateICmp(NewPred, Masked, Mask);
792 }
793 }
794
795 return nullptr;
796}
797
Sanjay Patel18549272015-09-08 18:24:36 +0000798/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000799Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
800 Instruction &CxtI) {
801 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
802 // if K1 and K2 are a one-bit mask.
803 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
804 return V;
805
Sanjay Patel519a87a2017-04-05 17:38:34 +0000806 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000807
808 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000809 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000810 if (LHS->getOperand(0) == RHS->getOperand(1) &&
811 LHS->getOperand(1) == RHS->getOperand(0))
812 LHS->swapOperands();
813 if (LHS->getOperand(0) == RHS->getOperand(0) &&
814 LHS->getOperand(1) == RHS->getOperand(1)) {
815 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
816 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
817 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000818 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000819 }
820 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000821
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000822 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000823 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000824 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000825
Erik Ecksteind1817522014-12-03 10:39:15 +0000826 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
827 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
828 return V;
829
830 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
831 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
832 return V;
833
Sanjay Patelef9f5862017-04-15 17:55:06 +0000834 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
835 return V;
836
Chris Lattner0a8191e2010-01-05 07:50:36 +0000837 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000838 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000839 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
840 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
841 if (!LHSC || !RHSC)
842 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000843
Sanjay Patel519a87a2017-04-05 17:38:34 +0000844 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000845 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000846 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000847 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000848 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
849 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000850 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000851 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000852 }
853 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000854
Benjamin Kramer101720f2011-04-28 20:09:57 +0000855 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000856 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000857 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000858 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
859 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000860 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000861 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000862
863 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000864 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000865 if (match(RHS0, m_Trunc(m_Value(V))) &&
866 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 SmallC = RHSC;
868 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000869 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
870 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000871 SmallC = LHSC;
872 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000873 }
874
Sanjay Patel519a87a2017-04-05 17:38:34 +0000875 if (SmallC && BigC) {
876 unsigned BigBitSize = BigC->getType()->getBitWidth();
877 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000878
879 // Check that the low bits are zero.
880 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000881 if ((Low & AndC->getValue()).isNullValue() &&
882 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000883 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
884 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
885 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
886 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000887 }
888 }
889 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000890
Chris Lattner0a8191e2010-01-05 07:50:36 +0000891 // From here on, we only handle:
892 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000893 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000894 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000895
Sanjay Patel519a87a2017-04-05 17:38:34 +0000896 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
897 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
898 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
899 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
900 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000901 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000902
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000904 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000905 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000906
Chris Lattner0a8191e2010-01-05 07:50:36 +0000907 // Ensure that the larger constant is on the RHS.
908 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000909 if (CmpInst::isSigned(PredL) ||
910 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000911 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000912 else
913 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000914
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 if (ShouldSwap) {
916 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000917 std::swap(LHSC, RHSC);
918 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000919 }
920
Dan Gohman4a618822010-02-10 16:03:48 +0000921 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000922 // comparing a value against two constants and and'ing the result
923 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000924 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
925 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000926 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000927 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000928
Sanjay Patel519a87a2017-04-05 17:38:34 +0000929 switch (PredL) {
930 default:
931 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000932 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000933 switch (PredR) {
934 default:
935 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000936 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000937 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000938 return Builder->CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000939 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000940 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000941 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000942 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000944 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000945 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000946 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000947 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000948 // Potential folds for this case should already be handled.
949 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000950 }
951 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000953 switch (PredR) {
954 default:
955 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000957 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000958 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000959 break; // (X u> 13 & X != 15) -> no change
960 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000961 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
962 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000963 }
964 break;
965 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000966 switch (PredR) {
967 default:
968 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000969 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000970 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000971 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000972 break; // (X s> 13 & X != 15) -> no change
973 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000974 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000975 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000976 }
977 break;
978 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000979
Craig Topperf40110f2014-04-25 05:29:35 +0000980 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000981}
982
Sanjay Patel18549272015-09-08 18:24:36 +0000983/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
984/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000985Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000986 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
987 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
988 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
989
990 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
991 // Swap RHS operands to match LHS.
992 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
993 std::swap(Op1LHS, Op1RHS);
994 }
995
996 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
997 // Suppose the relation between x and y is R, where R is one of
998 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
999 // testing the desired relations.
1000 //
1001 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1002 // bool(R & CC0) && bool(R & CC1)
1003 // = bool((R & CC0) & (R & CC1))
1004 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1005 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1006 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1007 Builder);
1008
Chris Lattner0a8191e2010-01-05 07:50:36 +00001009 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1010 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001011 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001012 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001013
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1015 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1016 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1017 // If either of the constants are nans, then the whole thing returns
1018 // false.
1019 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001020 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001021 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001023
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024 // Handle vector zeros. This occurs because the canonical form of
1025 // "fcmp ord x,x" is "fcmp ord x, 0".
1026 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1027 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001028 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001029 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001030 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001031
Craig Topperf40110f2014-04-25 05:29:35 +00001032 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001033}
1034
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001035/// Match De Morgan's Laws:
1036/// (~A & ~B) == (~(A | B))
1037/// (~A | ~B) == (~(A & B))
1038static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001039 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001040 auto Opcode = I.getOpcode();
1041 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1042 "Trying to match De Morgan's Laws with something other than and/or");
1043
Sanjay Patel7caaa792017-05-09 20:05:05 +00001044 // Flip the logic operation.
1045 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1046
1047 Value *A, *B;
1048 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1049 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1050 !IsFreeToInvert(A, A->hasOneUse()) &&
1051 !IsFreeToInvert(B, B->hasOneUse())) {
1052 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1053 return BinaryOperator::CreateNot(AndOr);
1054 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001055
1056 return nullptr;
1057}
1058
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001059bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1060 Value *CastSrc = CI->getOperand(0);
1061
1062 // Noop casts and casts of constants should be eliminated trivially.
1063 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1064 return false;
1065
1066 // If this cast is paired with another cast that can be eliminated, we prefer
1067 // to have it eliminated.
1068 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1069 if (isEliminableCastPair(PrecedingCI, CI))
1070 return false;
1071
1072 // If this is a vector sext from a compare, then we don't want to break the
1073 // idiom where each element of the extended vector is either zero or all ones.
1074 if (CI->getOpcode() == Instruction::SExt &&
1075 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1076 return false;
1077
1078 return true;
1079}
1080
Sanjay Patel60312bc42016-09-12 00:16:23 +00001081/// Fold {and,or,xor} (cast X), C.
1082static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1083 InstCombiner::BuilderTy *Builder) {
1084 Constant *C;
1085 if (!match(Logic.getOperand(1), m_Constant(C)))
1086 return nullptr;
1087
1088 auto LogicOpc = Logic.getOpcode();
1089 Type *DestTy = Logic.getType();
1090 Type *SrcTy = Cast->getSrcTy();
1091
Sanjay Pateld1e81192017-06-22 15:46:54 +00001092 // Move the logic operation ahead of a zext if the constant is unchanged in
1093 // the smaller source type. Performing the logic in a smaller type may provide
1094 // more information to later folds, and the smaller logic instruction may be
1095 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001096 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001097 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1098 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1099 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1100 if (ZextTruncC == C) {
1101 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1102 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1103 return new ZExtInst(NewOp, DestTy);
1104 }
1105 }
1106
1107 return nullptr;
1108}
1109
1110/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001111Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001112 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001113 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001114
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001116 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001117 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001118 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001119
Sanjay Patel9bba7502016-03-03 19:19:04 +00001120 // This must be a cast from an integer or integer vector source type to allow
1121 // transformation of the logic operation to the source type.
1122 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001123 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001124 if (!SrcTy->isIntOrIntVectorTy())
1125 return nullptr;
1126
Sanjay Patel60312bc42016-09-12 00:16:23 +00001127 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1128 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001129
Sanjay Patel9bba7502016-03-03 19:19:04 +00001130 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1131 if (!Cast1)
1132 return nullptr;
1133
1134 // Both operands of the logic operation are casts. The casts must be of the
1135 // same type for reduction.
1136 auto CastOpcode = Cast0->getOpcode();
1137 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001138 return nullptr;
1139
1140 Value *Cast0Src = Cast0->getOperand(0);
1141 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001142
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001143 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001144 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001145 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1146 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001147 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001148 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001149
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001150 // For now, only 'and'/'or' have optimizations after this.
1151 if (LogicOpc == Instruction::Xor)
1152 return nullptr;
1153
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001154 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001155 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001156 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1157 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1158 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001159 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001160 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001161 if (Res)
1162 return CastInst::Create(CastOpcode, Res, DestTy);
1163 return nullptr;
1164 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001165
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001166 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001167 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001168 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1169 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1170 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001171 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1172 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001173 if (Res)
1174 return CastInst::Create(CastOpcode, Res, DestTy);
1175 return nullptr;
1176 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001177
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001178 return nullptr;
1179}
1180
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001181static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1183
1184 // Canonicalize SExt or Not to the LHS
1185 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1186 std::swap(Op0, Op1);
1187 }
1188
1189 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1190 Value *X = nullptr;
1191 if (match(Op0, m_SExt(m_Value(X))) &&
1192 X->getType()->getScalarType()->isIntegerTy(1)) {
1193 Value *Zero = Constant::getNullValue(Op1->getType());
1194 return SelectInst::Create(X, Op1, Zero);
1195 }
1196
1197 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1198 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1199 X->getType()->getScalarType()->isIntegerTy(1)) {
1200 Value *Zero = Constant::getNullValue(Op0->getType());
1201 return SelectInst::Create(X, Zero, Op1);
1202 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001203
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001204 return nullptr;
1205}
1206
Sanjay Patele0c26e02017-04-23 22:00:02 +00001207static Instruction *foldAndToXor(BinaryOperator &I,
1208 InstCombiner::BuilderTy &Builder) {
1209 assert(I.getOpcode() == Instruction::And);
1210 Value *Op0 = I.getOperand(0);
1211 Value *Op1 = I.getOperand(1);
1212 Value *A, *B;
1213
1214 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1215 // (A | B) & ~(A & B) --> A ^ B
1216 // (A | B) & ~(B & A) --> A ^ B
1217 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1218 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1219 return BinaryOperator::CreateXor(A, B);
1220
1221 // (A | ~B) & (~A | B) --> ~(A ^ B)
1222 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1223 // (~B | A) & (~A | B) --> ~(A ^ B)
1224 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001225 if (Op0->hasOneUse() || Op1->hasOneUse())
1226 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1227 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1228 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001229
1230 return nullptr;
1231}
1232
1233static Instruction *foldOrToXor(BinaryOperator &I,
1234 InstCombiner::BuilderTy &Builder) {
1235 assert(I.getOpcode() == Instruction::Or);
1236 Value *Op0 = I.getOperand(0);
1237 Value *Op1 = I.getOperand(1);
1238 Value *A, *B;
1239
1240 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1241 // (A & B) | ~(A | B) --> ~(A ^ B)
1242 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001243 if (Op0->hasOneUse() || Op1->hasOneUse())
1244 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1245 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1246 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001247
1248 // (A & ~B) | (~A & B) --> A ^ B
1249 // (A & ~B) | (B & ~A) --> A ^ B
1250 // (~B & A) | (~A & B) --> A ^ B
1251 // (~B & A) | (B & ~A) --> A ^ B
1252 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1253 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1254 return BinaryOperator::CreateXor(A, B);
1255
1256 return nullptr;
1257}
1258
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001259// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1260// here. We should standardize that construct where it is needed or choose some
1261// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001263 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1265
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001266 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001267 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001268
Craig Toppera4205622017-06-09 03:21:29 +00001269 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001270 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001271
Craig Topper9d4171a2012-12-20 07:09:41 +00001272 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273 // purpose is to compute bits we don't care about.
1274 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001275 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001276
Sanjay Patele0c26e02017-04-23 22:00:02 +00001277 // Do this before using distributive laws to catch simple and/or/not patterns.
1278 if (Instruction *Xor = foldAndToXor(I, *Builder))
1279 return Xor;
1280
1281 // (A|B)&(A|C) -> A|(B&C) etc
1282 if (Value *V = SimplifyUsingDistributiveLaws(I))
1283 return replaceInstUsesWith(I, V);
1284
Craig Topper95e41422017-07-06 16:24:23 +00001285 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001286 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001287
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1289 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001290
1291 // Optimize a variety of ((val OP C1) & C2) combinations...
1292 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1293 Value *Op0LHS = Op0I->getOperand(0);
1294 Value *Op0RHS = Op0I->getOperand(1);
1295 switch (Op0I->getOpcode()) {
1296 default: break;
1297 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001298 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001299 // If the mask is only needed on one incoming arm, push it up.
1300 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001301
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001302 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001303 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001304 // Not masking anything out for the LHS, move to RHS.
1305 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1306 Op0RHS->getName()+".masked");
1307 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1308 }
1309 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001310 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001311 // Not masking anything out for the RHS, move to LHS.
1312 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1313 Op0LHS->getName()+".masked");
1314 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1315 }
1316
1317 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001318 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001320 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001321 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001322 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1323
Chris Lattner0a8191e2010-01-05 07:50:36 +00001324 break;
1325
1326 case Instruction::Shl:
1327 case Instruction::LShr:
1328 // (1 << x) & 1 --> zext(x == 0)
1329 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001330 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001331 Value *NewICmp =
1332 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1333 return new ZExtInst(NewICmp, I.getType());
1334 }
1335 break;
1336 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001337
David Majnemerde55c602017-01-17 18:08:06 +00001338 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1339 // of X and OP behaves well when given trunc(C1) and X.
1340 switch (Op0I->getOpcode()) {
1341 default:
1342 break;
1343 case Instruction::Xor:
1344 case Instruction::Or:
1345 case Instruction::Mul:
1346 case Instruction::Add:
1347 case Instruction::Sub:
1348 Value *X;
1349 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001350 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001351 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1352 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1353 Value *BinOp;
1354 if (isa<ZExtInst>(Op0LHS))
1355 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1356 else
1357 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1358 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1359 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1360 return new ZExtInst(And, I.getType());
1361 }
1362 }
1363 }
1364
Chris Lattner0a8191e2010-01-05 07:50:36 +00001365 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1366 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1367 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001368 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001369
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001370 // If this is an integer truncation, and if the source is an 'and' with
1371 // immediate, transform it. This frequently occurs for bitfield accesses.
1372 {
Craig Topperf40110f2014-04-25 05:29:35 +00001373 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001374 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1375 // Change: and (trunc (and X, YC) to T), C2
1376 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001377 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001378 // other simplifications.
1379 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1380 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1381 C3 = ConstantExpr::getAnd(C3, AndRHS);
1382 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001383 }
1384 }
Craig Topper86173602017-04-04 20:26:25 +00001385 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001386
Craig Topper86173602017-04-04 20:26:25 +00001387 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001388 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1389 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001390
Sanjay Patel7caaa792017-05-09 20:05:05 +00001391 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001392 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001393
Chris Lattner0a8191e2010-01-05 07:50:36 +00001394 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001395 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001396 // A&(A^B) => A & ~B
1397 {
1398 Value *tmpOp0 = Op0;
1399 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001400 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001401 if (A == Op1 || B == Op1 ) {
1402 tmpOp1 = Op0;
1403 tmpOp0 = Op1;
1404 // Simplify below
1405 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001406 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001407
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001408 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001409 if (B == tmpOp0) {
1410 std::swap(A, B);
1411 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001412 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001413 // A is originally -1 (or a vector of -1 and undefs), then we enter
1414 // an endless loop. By checking that A is non-constant we ensure that
1415 // we will never get to the loop.
1416 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001417 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001418 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001419 }
1420
1421 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001422 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001423 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001424 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001425 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001426
1427 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1428 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1429 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001430 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001431 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1432
1433 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1434 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1435 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001436 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001437 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001438
1439 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001440 // (A | B) & (B ^ (~A)) -> (A & B)
1441 // (B | A) & ((~A) ^ B) -> (A & B)
1442 // (B | A) & (B ^ (~A)) -> (A & B)
1443 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1444 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001445 return BinaryOperator::CreateAnd(A, B);
1446
1447 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001448 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001449 // (B ^ (~A)) & (A | B) -> (A & B)
1450 // (B ^ (~A)) & (B | A) -> (A & B)
1451 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001452 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001453 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001454 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001455
David Majnemer5e96f1b2014-08-30 06:18:20 +00001456 {
1457 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1458 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1459 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001460 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001461 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001462
David Majnemer5e96f1b2014-08-30 06:18:20 +00001463 // TODO: Make this recursive; it's a little tricky because an arbitrary
1464 // number of 'and' instructions might have to be created.
1465 Value *X, *Y;
1466 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1467 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001468 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001469 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001470 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001471 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001472 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001473 }
1474 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1475 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001476 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001477 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001478 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001479 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001480 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001481 }
1482 }
1483
Chris Lattner4e8137d2010-02-11 06:26:33 +00001484 // If and'ing two fcmp, try combine them into one.
1485 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1486 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001487 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001488 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001489
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001490 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1491 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001492
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001493 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1494 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001495
Craig Topperf40110f2014-04-25 05:29:35 +00001496 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001497}
1498
Chad Rosiera00df492016-05-25 16:22:14 +00001499/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1500/// insert the new intrinsic and return it.
1501Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1503
1504 // Look through zero extends.
1505 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1506 Op0 = Ext->getOperand(0);
1507
1508 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1509 Op1 = Ext->getOperand(0);
1510
1511 // (A | B) | C and A | (B | C) -> bswap if possible.
1512 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1513 match(Op1, m_Or(m_Value(), m_Value()));
1514
1515 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1516 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1517 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1518
1519 // (A & B) | (C & D) -> bswap if possible.
1520 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1521 match(Op1, m_And(m_Value(), m_Value()));
1522
1523 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1524 return nullptr;
1525
James Molloyf01488e2016-01-15 09:20:19 +00001526 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001527 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001528 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001529 Instruction *LastInst = Insts.pop_back_val();
1530 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001531
James Molloyf01488e2016-01-15 09:20:19 +00001532 for (auto *Inst : Insts)
1533 Worklist.Add(Inst);
1534 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001535}
1536
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001537/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1538static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1539 unsigned NumElts = C1->getType()->getVectorNumElements();
1540 for (unsigned i = 0; i != NumElts; ++i) {
1541 Constant *EltC1 = C1->getAggregateElement(i);
1542 Constant *EltC2 = C2->getAggregateElement(i);
1543 if (!EltC1 || !EltC2)
1544 return false;
1545
1546 // One element must be all ones, and the other must be all zeros.
1547 // FIXME: Allow undef elements.
1548 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1549 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1550 return false;
1551 }
1552 return true;
1553}
1554
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001555/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1556/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1557/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001558static Value *getSelectCondition(Value *A, Value *B,
1559 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001560 // If these are scalars or vectors of i1, A can be used directly.
1561 Type *Ty = A->getType();
1562 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1563 return A;
1564
1565 // If A and B are sign-extended, look through the sexts to find the booleans.
1566 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001567 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001568 if (match(A, m_SExt(m_Value(Cond))) &&
1569 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001570 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1571 NotB = peekThroughBitcast(NotB, true);
1572 if (match(NotB, m_SExt(m_Specific(Cond))))
1573 return Cond;
1574 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001575
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001576 // All scalar (and most vector) possibilities should be handled now.
1577 // Try more matches that only apply to non-splat constant vectors.
1578 if (!Ty->isVectorTy())
1579 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001580
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001581 // If both operands are constants, see if the constants are inverse bitmasks.
1582 Constant *AC, *BC;
1583 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1584 areInverseVectorBitmasks(AC, BC))
1585 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1586
1587 // If both operands are xor'd with constants using the same sexted boolean
1588 // operand, see if the constants are inverse bitmasks.
1589 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1590 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1591 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1592 areInverseVectorBitmasks(AC, BC)) {
1593 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1594 return Builder.CreateXor(Cond, AC);
1595 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001596 return nullptr;
1597}
1598
1599/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1600/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001601static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001602 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001603 // The potential condition of the select may be bitcasted. In that case, look
1604 // through its bitcast and the corresponding bitcast of the 'not' condition.
1605 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001606 A = peekThroughBitcast(A, true);
1607 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001608
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001609 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001610 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001611 // The bitcasts will either all exist or all not exist. The builder will
1612 // not create unnecessary casts if the types already match.
1613 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1614 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1615 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1616 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001617 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001618
Craig Topperf40110f2014-04-25 05:29:35 +00001619 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001620}
1621
Sanjay Patel18549272015-09-08 18:24:36 +00001622/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001623Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001624 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001625 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1626 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001627 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1628 return V;
1629
1630 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1631
Sanjay Patel519a87a2017-04-05 17:38:34 +00001632 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1633 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001634
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001635 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1636 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1637 // The original condition actually refers to the following two ranges:
1638 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1639 // We can fold these two ranges if:
1640 // 1) C1 and C2 is unsigned greater than C3.
1641 // 2) The two ranges are separated.
1642 // 3) C1 ^ C2 is one-bit mask.
1643 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1644 // This implies all values in the two ranges differ by exactly one bit.
1645
Sanjay Patel519a87a2017-04-05 17:38:34 +00001646 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1647 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1648 LHSC->getType() == RHSC->getType() &&
1649 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001650
1651 Value *LAdd = LHS->getOperand(0);
1652 Value *RAdd = RHS->getOperand(0);
1653
1654 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001655 ConstantInt *LAddC, *RAddC;
1656 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1657 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1658 LAddC->getValue().ugt(LHSC->getValue()) &&
1659 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001660
Sanjay Patel519a87a2017-04-05 17:38:34 +00001661 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1662 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1663 ConstantInt *MaxAddC = nullptr;
1664 if (LAddC->getValue().ult(RAddC->getValue()))
1665 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001666 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001667 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001668
Sanjay Patel519a87a2017-04-05 17:38:34 +00001669 APInt RRangeLow = -RAddC->getValue();
1670 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1671 APInt LRangeLow = -LAddC->getValue();
1672 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001673 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1674 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1675 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1676 : RRangeLow - LRangeLow;
1677
1678 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001679 RangeDiff.ugt(LHSC->getValue())) {
1680 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001681
Sanjay Patel519a87a2017-04-05 17:38:34 +00001682 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1683 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1684 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001685 }
1686 }
1687 }
1688 }
1689
Chris Lattner0a8191e2010-01-05 07:50:36 +00001690 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001691 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001692 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1693 LHS->getOperand(1) == RHS->getOperand(0))
1694 LHS->swapOperands();
1695 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1696 LHS->getOperand(1) == RHS->getOperand(1)) {
1697 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1698 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1699 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001700 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001701 }
1702 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001703
1704 // handle (roughly):
1705 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001706 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001707 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001708
Sanjay Patele4159d22017-04-10 19:38:36 +00001709 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001710 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1711 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1712 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001713 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001714 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001715 B = LHS0;
1716 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1717 A = RHS0;
1718 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001719 A = RHS->getOperand(1);
1720 }
1721 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1722 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001723 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001724 B = RHS0;
1725 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1726 A = LHS0;
1727 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001728 A = LHS->getOperand(1);
1729 }
1730 if (A && B)
1731 return Builder->CreateICmp(
1732 ICmpInst::ICMP_UGE,
1733 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1734 }
1735
Erik Ecksteind1817522014-12-03 10:39:15 +00001736 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1737 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1738 return V;
1739
1740 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1741 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1742 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001743
Sanjay Patelef9f5862017-04-15 17:55:06 +00001744 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1745 return V;
1746
David Majnemerc2a990b2013-07-05 00:31:17 +00001747 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001748 if (!LHSC || !RHSC)
1749 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001750
Sanjay Patel519a87a2017-04-05 17:38:34 +00001751 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001752 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001753 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001754 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001755 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001756 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001757 }
1758
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001759 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001760 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001761 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1762 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001763 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001764 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001765 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001766 }
1767
Chris Lattner0a8191e2010-01-05 07:50:36 +00001768 // From here on, we only handle:
1769 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001770 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001771 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001772
Sanjay Patel519a87a2017-04-05 17:38:34 +00001773 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1774 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1775 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1776 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1777 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001778 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001779
Chris Lattner0a8191e2010-01-05 07:50:36 +00001780 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001781 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001782 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001783
Chris Lattner0a8191e2010-01-05 07:50:36 +00001784 // Ensure that the larger constant is on the RHS.
1785 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001786 if (CmpInst::isSigned(PredL) ||
1787 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001788 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001789 else
1790 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001791
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 if (ShouldSwap) {
1793 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001794 std::swap(LHSC, RHSC);
1795 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001796 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001797
Dan Gohman4a618822010-02-10 16:03:48 +00001798 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 // comparing a value against two constants and or'ing the result
1800 // together. Because of the above check, we know that we only have
1801 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1802 // icmp folding check above), that the two constants are not
1803 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001804 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805
Sanjay Patel519a87a2017-04-05 17:38:34 +00001806 switch (PredL) {
1807 default:
1808 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001810 switch (PredR) {
1811 default:
1812 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001813 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001814 // Potential folds for this case should already be handled.
1815 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001816 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1817 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001818 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819 }
1820 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001822 switch (PredR) {
1823 default:
1824 llvm_unreachable("Unknown integer condition code!");
1825 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001826 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001827 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001828 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001829 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1830 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831 }
1832 break;
1833 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001834 switch (PredR) {
1835 default:
1836 llvm_unreachable("Unknown integer condition code!");
1837 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001839 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001840 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001841 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001842 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001843 }
1844 break;
1845 }
Craig Topperf40110f2014-04-25 05:29:35 +00001846 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001847}
1848
Sanjay Patel18549272015-09-08 18:24:36 +00001849/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1850/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001851Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001852 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1853 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1854 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1855
1856 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1857 // Swap RHS operands to match LHS.
1858 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1859 std::swap(Op1LHS, Op1RHS);
1860 }
1861
1862 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1863 // This is a similar transformation to the one in FoldAndOfFCmps.
1864 //
1865 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1866 // bool(R & CC0) || bool(R & CC1)
1867 // = bool((R & CC0) | (R & CC1))
1868 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1869 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1870 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1871 Builder);
1872
Chris Lattner0a8191e2010-01-05 07:50:36 +00001873 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001874 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001875 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1876 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1877 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1878 // If either of the constants are nans, then the whole thing returns
1879 // true.
1880 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001881 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001882
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883 // Otherwise, no need to compare the two constants, compare the
1884 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001885 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001886 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001887
Chris Lattner0a8191e2010-01-05 07:50:36 +00001888 // Handle vector zeros. This occurs because the canonical form of
1889 // "fcmp uno x,x" is "fcmp uno x, 0".
1890 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1891 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001892 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001893
Craig Topperf40110f2014-04-25 05:29:35 +00001894 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001895 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001896
Craig Topperf40110f2014-04-25 05:29:35 +00001897 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001898}
1899
Sanjay Patel18549272015-09-08 18:24:36 +00001900/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001901///
1902/// ((A | B) & C1) | (B & C2)
1903///
1904/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001905///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001906/// (A & C1) | B
1907///
1908/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001909static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1910 Value *A, Value *B, Value *C,
1911 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001912 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001913 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001914
Craig Topperf40110f2014-04-25 05:29:35 +00001915 Value *V1 = nullptr;
1916 ConstantInt *CI2 = nullptr;
1917 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001918
1919 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001920 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001921
1922 if (V1 == A || V1 == B) {
1923 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1924 return BinaryOperator::CreateOr(NewOp, V1);
1925 }
1926
Craig Topperf40110f2014-04-25 05:29:35 +00001927 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001928}
1929
David Majnemer5d1aeba2014-08-21 05:14:48 +00001930/// \brief This helper function folds:
1931///
Craig Toppera074c102017-06-21 18:57:00 +00001932/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001933///
1934/// into:
1935///
1936/// (A & C1) ^ B
1937///
1938/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001939static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1940 Value *A, Value *B, Value *C,
1941 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001942 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1943 if (!CI1)
1944 return nullptr;
1945
1946 Value *V1 = nullptr;
1947 ConstantInt *CI2 = nullptr;
1948 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1949 return nullptr;
1950
1951 APInt Xor = CI1->getValue() ^ CI2->getValue();
1952 if (!Xor.isAllOnesValue())
1953 return nullptr;
1954
1955 if (V1 == A || V1 == B) {
1956 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1957 return BinaryOperator::CreateXor(NewOp, V1);
1958 }
1959
1960 return nullptr;
1961}
1962
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001963// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1964// here. We should standardize that construct where it is needed or choose some
1965// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001966Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001967 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1969
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001970 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001971 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001972
Craig Toppera4205622017-06-09 03:21:29 +00001973 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001974 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001975
Craig Topper9d4171a2012-12-20 07:09:41 +00001976 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 // purpose is to compute bits we don't care about.
1978 if (SimplifyDemandedInstructionBits(I))
1979 return &I;
1980
Sanjay Patele0c26e02017-04-23 22:00:02 +00001981 // Do this before using distributive laws to catch simple and/or/not patterns.
1982 if (Instruction *Xor = foldOrToXor(I, *Builder))
1983 return Xor;
1984
1985 // (A&B)|(A&C) -> A&(B|C) etc
1986 if (Value *V = SimplifyUsingDistributiveLaws(I))
1987 return replaceInstUsesWith(I, V);
1988
Craig Topper95e41422017-07-06 16:24:23 +00001989 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001990 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001991
Craig Topper86173602017-04-04 20:26:25 +00001992 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001993 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1994 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001995
Chad Rosiere5819e22016-05-26 14:58:51 +00001996 // Given an OR instruction, check to see if this is a bswap.
1997 if (Instruction *BSwap = MatchBSwap(I))
1998 return BSwap;
1999
Craig Topperafa07c52017-04-09 06:12:41 +00002000 {
2001 Value *A;
2002 const APInt *C;
2003 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2004 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2005 MaskedValueIsZero(Op1, *C, 0, &I)) {
2006 Value *NOr = Builder->CreateOr(A, Op1);
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
Craig Topperafa07c52017-04-09 06:12:41 +00002012 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2013 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2014 MaskedValueIsZero(Op0, *C, 0, &I)) {
2015 Value *NOr = Builder->CreateOr(A, Op0);
2016 NOr->takeName(Op0);
2017 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002018 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002019 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002020 }
2021
Craig Topperafa07c52017-04-09 06:12:41 +00002022 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023
Suyog Sardad64faf62014-07-22 18:09:41 +00002024 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002025 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2026 return BinaryOperator::CreateOr(A, Op1);
2027 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2028 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002029
2030 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002031 // The NOT is guaranteed to be in the RHS by complexity ordering.
2032 if (match(Op1, m_Not(m_Value(A))) &&
2033 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2034 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002035
Chris Lattner0a8191e2010-01-05 07:50:36 +00002036 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002037 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2039 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002040 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002041 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2042 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002043 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002044 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002045 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002046 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002047 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002048 ((V1 == B &&
2049 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2050 (V2 == B &&
2051 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002052 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002053 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002054 // Or commutes, try both ways.
2055 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002056 ((V1 == A &&
2057 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2058 (V2 == A &&
2059 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002060 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002061 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002062
Chris Lattner95188692010-01-11 06:55:24 +00002063 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002064 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002065 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002066 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002067 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002068 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002069 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002070 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2071 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002072 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002073 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002074 }
2075 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002076
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002077 // Don't try to form a select if it's unlikely that we'll get rid of at
2078 // least one of the operands. A select is generally more expensive than the
2079 // 'or' that it is replacing.
2080 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2081 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2082 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2083 return replaceInstUsesWith(I, V);
2084 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2085 return replaceInstUsesWith(I, V);
2086 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2087 return replaceInstUsesWith(I, V);
2088 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2089 return replaceInstUsesWith(I, V);
2090 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2097 return replaceInstUsesWith(I, V);
2098 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002099
Benjamin Kramer11743242010-07-12 13:34:22 +00002100 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002101 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2102 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2103 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002104 }
2105 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002106 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2107 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2108 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002109 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002110 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002111 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2112 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2113 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002114 }
2115 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002116 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2117 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2118 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002119 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002120 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002121
David Majnemer42af3602014-07-30 21:26:37 +00002122 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2123 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2124 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002125 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002126
2127 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2128 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2129 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002130 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002131
David Majnemerf1eda232014-08-14 06:41:38 +00002132 // ((B | C) & A) | B -> B | (A & C)
2133 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2134 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2135
Sanjay Patel7caaa792017-05-09 20:05:05 +00002136 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002137 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002138
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002139 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002140 bool SwappedForXor = false;
2141 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002142 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002143 SwappedForXor = true;
2144 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002145
2146 // A | ( A ^ B) -> A | B
2147 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002148 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002149 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2150 if (Op0 == A || Op0 == B)
2151 return BinaryOperator::CreateOr(A, B);
2152
Chad Rosier7813dce2012-04-26 23:29:14 +00002153 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2154 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2155 return BinaryOperator::CreateOr(A, B);
2156
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002157 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2158 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2159 return BinaryOperator::CreateOr(Not, Op0);
2160 }
2161 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2162 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2163 return BinaryOperator::CreateOr(Not, Op0);
2164 }
2165 }
2166
2167 // A | ~(A | B) -> A | ~B
2168 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002169 if (match(Op1, m_Not(m_Value(A))))
2170 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002171 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2172 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2173 B->getOpcode() == Instruction::Xor)) {
2174 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2175 B->getOperand(0);
2176 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2177 return BinaryOperator::CreateOr(Not, Op0);
2178 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002179
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002180 // (A & B) | (~A ^ B) -> (~A ^ B)
2181 // (A & B) | (B ^ ~A) -> (~A ^ B)
2182 // (B & A) | (~A ^ B) -> (~A ^ B)
2183 // (B & A) | (B ^ ~A) -> (~A ^ B)
2184 // The match order is important: match the xor first because the 'not'
2185 // operation defines 'A'. We do not need to match the xor as Op0 because the
2186 // xor was canonicalized to Op1 above.
2187 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2188 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002189 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2190
Eli Friedmane06535b2012-03-16 00:52:42 +00002191 if (SwappedForXor)
2192 std::swap(Op0, Op1);
2193
David Majnemer3d6f80b2014-11-28 19:58:29 +00002194 {
2195 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2196 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2197 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002198 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002199 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002200
David Majnemer3d6f80b2014-11-28 19:58:29 +00002201 // TODO: Make this recursive; it's a little tricky because an arbitrary
2202 // number of 'or' instructions might have to be created.
2203 Value *X, *Y;
2204 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2205 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002206 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002207 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002208 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002209 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002210 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002211 }
2212 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2213 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002214 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002215 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002216 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002217 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002218 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002219 }
2220 }
2221
Chris Lattner4e8137d2010-02-11 06:26:33 +00002222 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2223 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2224 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002225 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002226 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002227
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002228 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2229 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002230
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002231 // 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 +00002232 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002233 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002234 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002235 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002236 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002237 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2238
Owen Andersonc237a842010-09-13 17:59:27 +00002239 // Note: If we've gotten to the point of visiting the outer OR, then the
2240 // inner one couldn't be simplified. If it was a constant, then it won't
2241 // be simplified by a later pass either, so we try swapping the inner/outer
2242 // ORs in the hopes that we'll be able to simplify it this way.
2243 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002244 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002245 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2246 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2247 Value *Inner = Builder->CreateOr(A, Op1);
2248 Inner->takeName(Op0);
2249 return BinaryOperator::CreateOr(Inner, C1);
2250 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002251
Bill Wendling23242092013-02-16 23:41:36 +00002252 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2253 // Since this OR statement hasn't been optimized further yet, we hope
2254 // that this transformation will allow the new ORs to be optimized.
2255 {
Craig Topperf40110f2014-04-25 05:29:35 +00002256 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002257 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2258 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2259 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2260 Value *orTrue = Builder->CreateOr(A, C);
2261 Value *orFalse = Builder->CreateOr(B, D);
2262 return SelectInst::Create(X, orTrue, orFalse);
2263 }
2264 }
2265
Craig Topperf40110f2014-04-25 05:29:35 +00002266 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002267}
2268
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002269/// A ^ B can be specified using other logic ops in a variety of patterns. We
2270/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002271static Instruction *foldXorToXor(BinaryOperator &I,
2272 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002273 assert(I.getOpcode() == Instruction::Xor);
2274 Value *Op0 = I.getOperand(0);
2275 Value *Op1 = I.getOperand(1);
2276 Value *A, *B;
2277
2278 // There are 4 commuted variants for each of the basic patterns.
2279
2280 // (A & B) ^ (A | B) -> A ^ B
2281 // (A & B) ^ (B | A) -> A ^ B
2282 // (A | B) ^ (A & B) -> A ^ B
2283 // (A | B) ^ (B & A) -> A ^ B
2284 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2285 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2286 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2287 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2288 I.setOperand(0, A);
2289 I.setOperand(1, B);
2290 return &I;
2291 }
2292
2293 // (A | ~B) ^ (~A | B) -> A ^ B
2294 // (~B | A) ^ (~A | B) -> A ^ B
2295 // (~A | B) ^ (A | ~B) -> A ^ B
2296 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002297 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2298 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2299 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2300 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002301 I.setOperand(0, A);
2302 I.setOperand(1, B);
2303 return &I;
2304 }
2305
2306 // (A & ~B) ^ (~A & B) -> A ^ B
2307 // (~B & A) ^ (~A & B) -> A ^ B
2308 // (~A & B) ^ (A & ~B) -> A ^ B
2309 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002310 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2311 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2312 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2313 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002314 I.setOperand(0, A);
2315 I.setOperand(1, B);
2316 return &I;
2317 }
2318
Craig Topperf60ab472017-07-02 01:15:51 +00002319 // For the remaining cases we need to get rid of one of the operands.
2320 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2321 return nullptr;
2322
2323 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2324 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2325 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2326 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2327 // Complexity sorting ensures the not will be on the right side.
2328 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2329 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2330 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2331 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2332 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2333
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002334 return nullptr;
2335}
2336
Sanjay Patel5e456b92017-05-18 20:53:16 +00002337Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2338 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2339 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2340 LHS->getOperand(1) == RHS->getOperand(0))
2341 LHS->swapOperands();
2342 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2343 LHS->getOperand(1) == RHS->getOperand(1)) {
2344 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2345 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2346 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2347 bool isSigned = LHS->isSigned() || RHS->isSigned();
2348 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2349 }
2350 }
2351
Sanjay Pateladca8252017-06-20 12:40:55 +00002352 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2353 // into those logic ops. That is, try to turn this into an and-of-icmps
2354 // because we have many folds for that pattern.
2355 //
2356 // This is based on a truth table definition of xor:
2357 // X ^ Y --> (X | Y) & !(X & Y)
2358 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2359 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2360 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2361 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2362 // TODO: Independently handle cases where the 'and' side is a constant.
2363 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2364 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2365 RHS->setPredicate(RHS->getInversePredicate());
2366 return Builder->CreateAnd(LHS, RHS);
2367 }
2368 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002369 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002370 LHS->setPredicate(LHS->getInversePredicate());
2371 return Builder->CreateAnd(LHS, RHS);
2372 }
2373 }
2374 }
2375
Sanjay Patel5e456b92017-05-18 20:53:16 +00002376 return nullptr;
2377}
2378
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002379// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2380// here. We should standardize that construct where it is needed or choose some
2381// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002382Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002383 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2385
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002386 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002387 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002388
Craig Toppera4205622017-06-09 03:21:29 +00002389 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002390 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002391
Craig Topperf60ab472017-07-02 01:15:51 +00002392 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002393 return NewXor;
2394
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002395 // (A&B)^(A&C) -> A&(B^C) etc
2396 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002397 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002398
Craig Topper9d4171a2012-12-20 07:09:41 +00002399 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002400 // purpose is to compute bits we don't care about.
2401 if (SimplifyDemandedInstructionBits(I))
2402 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002403
Craig Topper95e41422017-07-06 16:24:23 +00002404 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002405 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002406
Sanjay Patel6381db12017-05-02 15:31:40 +00002407 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2408 Value *X, *Y;
2409
2410 // We must eliminate the and/or (one-use) for these transforms to not increase
2411 // the instruction count.
2412 // ~(~X & Y) --> (X | ~Y)
2413 // ~(Y & ~X) --> (X | ~Y)
2414 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2415 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2416 return BinaryOperator::CreateOr(X, NotY);
2417 }
2418 // ~(~X | Y) --> (X & ~Y)
2419 // ~(Y | ~X) --> (X & ~Y)
2420 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2421 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2422 return BinaryOperator::CreateAnd(X, NotY);
2423 }
2424
Sanjay Patel3b863f82017-04-22 18:05:35 +00002425 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002426 BinaryOperator *NotVal;
2427 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2428 if (NotVal->getOpcode() == Instruction::And ||
2429 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002430 // Apply DeMorgan's Law when inverts are free:
2431 // ~(X & Y) --> (~X | ~Y)
2432 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002433 if (IsFreeToInvert(NotVal->getOperand(0),
2434 NotVal->getOperand(0)->hasOneUse()) &&
2435 IsFreeToInvert(NotVal->getOperand(1),
2436 NotVal->getOperand(1)->hasOneUse())) {
2437 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2438 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2439 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002440 return BinaryOperator::CreateOr(NotX, NotY);
2441 return BinaryOperator::CreateAnd(NotX, NotY);
2442 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002443 }
2444
2445 // ~(~X >>s Y) --> (X >>s Y)
2446 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2447 return BinaryOperator::CreateAShr(X, Y);
2448
2449 // If we are inverting a right-shifted constant, we may be able to eliminate
2450 // the 'not' by inverting the constant and using the opposite shift type.
2451 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2452 // but we must check that in case that transform has not fired yet.
2453 const APInt *C;
2454 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2455 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2456 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2457 return BinaryOperator::CreateLShr(NotC, Y);
2458 }
2459
2460 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2461 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2462 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2463 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002464 }
2465 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002466
Craig Topper798a19a2017-06-29 00:07:08 +00002467 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002468 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002469 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002470 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2471 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002472 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002473
Craig Topper9d1821b2017-04-09 06:12:31 +00002474 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002475 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2476 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2477 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2478 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2479 Instruction::CastOps Opcode = Op0C->getOpcode();
2480 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002481 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002482 Op0C->getDestTy()))) {
2483 CI->setPredicate(CI->getInversePredicate());
2484 return CastInst::Create(Opcode, CI, Op0C->getType());
2485 }
2486 }
2487 }
2488 }
2489
2490 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2491 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper79ab6432017-07-06 18:39:47 +00002492 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isMinusOne())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002493 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2494 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002495 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2496 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002497 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002498
Chris Lattner0a8191e2010-01-05 07:50:36 +00002499 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2500 if (Op0I->getOpcode() == Instruction::Add) {
2501 // ~(X-c) --> (-c-1)-X
Craig Topper79ab6432017-07-06 18:39:47 +00002502 if (RHSC->isMinusOne()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002504 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2505 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002506 } else if (RHSC->getValue().isSignMask()) {
2507 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002508 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2510
2511 }
2512 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002513 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002514 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2515 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002516 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002517 // Anything in both C1 and C2 is known to be zero, remove it from
2518 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002519 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002520 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002521 ConstantExpr::getNot(CommonBits));
2522 Worklist.Add(Op0I);
2523 I.setOperand(0, Op0I->getOperand(0));
2524 I.setOperand(1, NewRHS);
2525 return &I;
2526 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002527 } else if (Op0I->getOpcode() == Instruction::LShr) {
2528 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2529 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002530 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002531 ConstantInt *C1;
2532 if (Op0I->hasOneUse() &&
2533 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2534 E1->getOpcode() == Instruction::Xor &&
2535 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2536 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002537 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002538 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2539 FoldConst ^= C3->getValue();
2540 // Prepare the two operands.
2541 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2542 Opnd0->takeName(Op0I);
2543 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2544 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2545
2546 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2547 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002548 }
2549 }
2550 }
Craig Topper86173602017-04-04 20:26:25 +00002551 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002552
Craig Topper86173602017-04-04 20:26:25 +00002553 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002554 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2555 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002556
Craig Topper76394602017-04-10 06:53:23 +00002557 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002558 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002559 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002560 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002561 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002562 std::swap(A, B);
2563 }
2564 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002565 I.swapOperands(); // Simplified below.
2566 std::swap(Op0, Op1);
2567 }
Craig Topper76394602017-04-10 06:53:23 +00002568 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002569 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002570 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002571 std::swap(A, B);
2572 }
2573 if (B == Op0) { // A^(B&A) -> (B&A)^A
2574 I.swapOperands(); // Simplified below.
2575 std::swap(Op0, Op1);
2576 }
2577 }
2578 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002579
Craig Topper76394602017-04-10 06:53:23 +00002580 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002581 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002582 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002583 if (A == Op1) // (B|A)^B == (A|B)^B
2584 std::swap(A, B);
2585 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002586 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002587 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002588 if (A == Op1) // (A&B)^A -> (B&A)^A
2589 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002590 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002591 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002592 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002593 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002594 }
2595 }
2596 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002597
Craig Topper76394602017-04-10 06:53:23 +00002598 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002599 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002600 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002601 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2602 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002603 if (D == A)
2604 return BinaryOperator::CreateXor(
2605 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2606 if (D == B)
2607 return BinaryOperator::CreateXor(
2608 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002609 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002610 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002611 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2612 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002613 if (D == A)
2614 return BinaryOperator::CreateXor(
2615 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2616 if (D == B)
2617 return BinaryOperator::CreateXor(
2618 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002619 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002620 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002621 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002622 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002623 return BinaryOperator::CreateOr(A, B);
2624 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002625 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002626 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002627 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002628 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002629
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002630 // (A & ~B) ^ ~A -> ~(A & B)
2631 // (~B & A) ^ ~A -> ~(A & B)
2632 Value *A, *B;
2633 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002634 match(Op1, m_Not(m_Specific(A))))
2635 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2636
Sanjay Patel5e456b92017-05-18 20:53:16 +00002637 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2638 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2639 if (Value *V = foldXorOfICmps(LHS, RHS))
2640 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002641
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002642 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2643 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002644
Craig Topperf40110f2014-04-25 05:29:35 +00002645 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002646}