blob: a23cad40a38c706afe6a032870913b5387cbfca9 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
57 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
61 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Chris Lattner067459c2010-03-05 08:46:26 +000067 InstCombiner::BuilderTy *Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner067459c2010-03-05 08:46:26 +000075 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
79/// \param I Binary operator to transform.
80/// \return Pointer to node that must replace the original binary operator, or
81/// null pointer if no transformation was made.
82Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
Craig Topperc6948c22017-07-03 05:54:11 +000083 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
84
Craig Topper22795de2017-07-06 16:24:21 +000085 Value *OldLHS = I.getOperand(0);
86 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000087
Craig Topper766ce6e2017-07-03 05:54:15 +000088 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000089 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000090 return nullptr;
91
Craig Topper766ce6e2017-07-03 05:54:15 +000092 Value *NewRHS;
93 const APInt *C;
94
Craig Topper22795de2017-07-06 16:24:21 +000095 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000096 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000097 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
98 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +000099 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000100 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000102 if (!OldLHS->hasOneUse())
103 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000104 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
105 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000106 return nullptr;
107
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000108 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000109 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
110 I.getType());
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000111 return Builder->CreateCall(F, BinOp);
112}
113
Sanjay Patel18549272015-09-08 18:24:36 +0000114/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000115/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
116Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000117 ConstantInt *OpRHS,
118 ConstantInt *AndRHS,
119 BinaryOperator &TheAnd) {
120 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000121 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000122 if (!Op->isShift())
123 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
124
125 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000126 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000127 case Instruction::Xor:
128 if (Op->hasOneUse()) {
129 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
130 Value *And = Builder->CreateAnd(X, AndRHS);
131 And->takeName(Op);
132 return BinaryOperator::CreateXor(And, Together);
133 }
134 break;
135 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000136 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000137 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
138 if (TogetherCI && !TogetherCI->isZero()){
139 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
140 // NOTE: This reduces the number of bits set in the & mask, which
141 // can expose opportunities for store narrowing.
142 Together = ConstantExpr::getXor(AndRHS, Together);
143 Value *And = Builder->CreateAnd(X, Together);
144 And->takeName(Op);
145 return BinaryOperator::CreateOr(And, OpRHS);
146 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000147 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000148
Chris Lattner0a8191e2010-01-05 07:50:36 +0000149 break;
150 case Instruction::Add:
151 if (Op->hasOneUse()) {
152 // Adding a one to a single bit bit-field should be turned into an XOR
153 // of the bit. First thing to check is to see if this AND is with a
154 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000155 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000156
157 // If there is only one bit set.
158 if (AndRHSV.isPowerOf2()) {
159 // Ok, at this point, we know that we are masking the result of the
160 // ADD down to exactly one bit. If the constant we are adding has
161 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000162 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000163
164 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000165 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000166 // If not, the only thing that can effect the output of the AND is
167 // the bit specified by AndRHSV. If that bit is set, the effect of
168 // the XOR is to toggle the bit. If it is clear, then the ADD has
169 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000170 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000171 TheAnd.setOperand(0, X);
172 return &TheAnd;
173 } else {
174 // Pull the XOR out of the AND.
175 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
176 NewAnd->takeName(Op);
177 return BinaryOperator::CreateXor(NewAnd, AndRHS);
178 }
179 }
180 }
181 }
182 break;
183
184 case Instruction::Shl: {
185 // We know that the AND will not produce any of the bits shifted in, so if
186 // the anded constant includes them, clear them now!
187 //
188 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
189 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
190 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000191 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000192
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000193 if (CI->getValue() == ShlMask)
194 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000195 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000196
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000197 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000198 TheAnd.setOperand(1, CI);
199 return &TheAnd;
200 }
201 break;
202 }
203 case Instruction::LShr: {
204 // We know that the AND will not produce any of the bits shifted in, so if
205 // the anded constant includes them, clear them now! This only applies to
206 // unsigned shifts, because a signed shr may bring in set bits!
207 //
208 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
209 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
210 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000211 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000212
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000213 if (CI->getValue() == ShrMask)
214 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000215 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000216
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000217 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000218 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
219 return &TheAnd;
220 }
221 break;
222 }
223 case Instruction::AShr:
224 // Signed shr.
225 // See if this is shifting in some sign extension, then masking it out
226 // with an and.
227 if (Op->hasOneUse()) {
228 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
229 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
230 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000231 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000232 if (C == AndRHS) { // Masking out bits shifted in.
233 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
234 // Make the argument unsigned.
235 Value *ShVal = Op->getOperand(0);
236 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
237 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
238 }
239 }
240 break;
241 }
Craig Topperf40110f2014-04-25 05:29:35 +0000242 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243}
244
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000245/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000246/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
247/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000248Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000249 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000250 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000251 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000252
Sanjay Patel85d79742016-08-31 19:49:56 +0000253 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000254 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000255 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000256
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000257 // V >= Min && V < Hi --> V < Hi
258 // V < Min || V >= Hi --> V >= Hi
259 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000260 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000261 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000262 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000263 }
264
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000265 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
266 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000267 Value *VMinusLo =
268 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
269 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000270 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000271}
272
Sanjay Patel77bf6222017-04-03 16:53:12 +0000273/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
274/// that can be simplified.
275/// One of A and B is considered the mask. The other is the value. This is
276/// described as the "AMask" or "BMask" part of the enum. If the enum contains
277/// only "Mask", then both A and B can be considered masks. If A is the mask,
278/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
279/// If both A and C are constants, this proof is also easy.
280/// For the following explanations, we assume that A is the mask.
281///
282/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
283/// bits of A are set in B.
284/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
285///
286/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
287/// bits of A are cleared in B.
288/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
289///
290/// "Mixed" declares that (A & B) == C and C might or might not contain any
291/// number of one bits and zero bits.
292/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
293///
294/// "Not" means that in above descriptions "==" should be replaced by "!=".
295/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
296///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000297/// If the mask A contains a single bit, then the following is equivalent:
298/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
299/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
300enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000301 AMask_AllOnes = 1,
302 AMask_NotAllOnes = 2,
303 BMask_AllOnes = 4,
304 BMask_NotAllOnes = 8,
305 Mask_AllZeros = 16,
306 Mask_NotAllZeros = 32,
307 AMask_Mixed = 64,
308 AMask_NotMixed = 128,
309 BMask_Mixed = 256,
310 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000311};
312
Sanjay Patel77bf6222017-04-03 16:53:12 +0000313/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
314/// satisfies.
315static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
316 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000317 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
318 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
319 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000320 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
321 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
322 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
323 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000324 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000325 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000326 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
327 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
328 if (IsAPow2)
329 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
330 : (AMask_AllOnes | AMask_Mixed));
331 if (IsBPow2)
332 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
333 : (BMask_AllOnes | BMask_Mixed));
334 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000335 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000336
Owen Anderson3fe002d2010-09-08 22:16:17 +0000337 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000338 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
339 : (AMask_NotAllOnes | AMask_NotMixed));
340 if (IsAPow2)
341 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
342 : (Mask_AllZeros | AMask_Mixed));
343 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
344 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000346
Craig Topperae48cb22012-12-20 07:15:54 +0000347 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
349 : (BMask_NotAllOnes | BMask_NotMixed));
350 if (IsBPow2)
351 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
352 : (Mask_AllZeros | BMask_Mixed));
353 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
354 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000355 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000356
357 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000358}
359
Tim Northoverc0756c42013-09-04 11:57:13 +0000360/// Convert an analysis of a masked ICmp into its equivalent if all boolean
361/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
362/// is adjacent to the corresponding normal flag (recording ==), this just
363/// involves swapping those bits over.
364static unsigned conjugateICmpMask(unsigned Mask) {
365 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000366 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
367 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000368 << 1;
369
Sanjay Patel77bf6222017-04-03 16:53:12 +0000370 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
371 AMask_NotMixed | BMask_NotMixed))
372 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000373
374 return NewMask;
375}
376
Sanjay Patel77bf6222017-04-03 16:53:12 +0000377/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
378/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
379/// RHS satisfy.
380static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
381 Value *&D, Value *&E, ICmpInst *LHS,
382 ICmpInst *RHS,
383 ICmpInst::Predicate &PredL,
384 ICmpInst::Predicate &PredR) {
385 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
386 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000387 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000388 if (LHS->getOperand(0)->getType()->isVectorTy())
389 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000390
391 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000392 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000393 // and L11 & L12 == L21 & L22. The same goes for RHS.
394 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000395 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000396 // above.
397 Value *L1 = LHS->getOperand(0);
398 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000399 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000400 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000401 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000402 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000403 } else {
404 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000405 if (!L1->getType()->isIntegerTy()) {
406 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000407 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000408 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
409 // Any icmp can be viewed as being trivially masked; if it allows us to
410 // remove one, it's worth it.
411 L11 = L1;
412 L12 = Constant::getAllOnesValue(L1->getType());
413 }
414
415 if (!L2->getType()->isIntegerTy()) {
416 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000417 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000418 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
419 L21 = L2;
420 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000421 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000422 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000423
424 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000425 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000426 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000427
428 Value *R1 = RHS->getOperand(0);
429 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000430 Value *R11, *R12;
431 bool Ok = false;
432 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000433 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000434 A = R11;
435 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000436 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000437 A = R12;
438 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000439 } else {
440 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000441 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000442 E = R2;
443 R1 = nullptr;
444 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000445 } else if (R1->getType()->isIntegerTy()) {
446 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
447 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000448 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000449 R11 = R1;
450 R12 = Constant::getAllOnesValue(R1->getType());
451 }
452
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000453 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000454 A = R11;
455 D = R12;
456 E = R2;
457 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000458 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000459 A = R12;
460 D = R11;
461 E = R2;
462 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000463 }
464 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000465
466 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000467 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000468 return 0;
469
Chad Rosier58919cc2016-05-09 21:37:43 +0000470 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000471 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000472 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
473 R11 = R2;
474 R12 = Constant::getAllOnesValue(R2->getType());
475 }
476
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000477 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000478 A = R11;
479 D = R12;
480 E = R1;
481 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000482 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000483 A = R12;
484 D = R11;
485 E = R1;
486 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000487 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000488 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000489 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000490 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000491 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000492 return 0;
493
494 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000495 B = L12;
496 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000497 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000498 B = L11;
499 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000500 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000501 B = L22;
502 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000503 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000504 B = L21;
505 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000506 }
507
Sanjay Patel77bf6222017-04-03 16:53:12 +0000508 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
509 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000510 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000511}
Sanjay Patel18549272015-09-08 18:24:36 +0000512
513/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
514/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000515static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
516 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000517 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000518 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
519 unsigned Mask =
520 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
521 if (Mask == 0)
522 return nullptr;
523
524 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
525 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000526
Tim Northoverc0756c42013-09-04 11:57:13 +0000527 // In full generality:
528 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
529 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
530 //
531 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
532 // equivalent to (icmp (A & X) !Op Y).
533 //
534 // Therefore, we can pretend for the rest of this function that we're dealing
535 // with the conjunction, provided we flip the sense of any comparisons (both
536 // input and output).
537
538 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000539 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000540 if (!IsAnd) {
541 // Convert the masking analysis into its equivalent with negated
542 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000543 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000544 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000545
Sanjay Patel77bf6222017-04-03 16:53:12 +0000546 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000547 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000548 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000549 Value *NewOr = Builder->CreateOr(B, D);
550 Value *NewAnd = Builder->CreateAnd(A, NewOr);
551 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000552 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000553 // with B and D, having a single bit set.
554 Value *Zero = Constant::getNullValue(A->getType());
555 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000556 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000557 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000558 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000560 Value *NewOr = Builder->CreateOr(B, D);
561 Value *NewAnd = Builder->CreateAnd(A, NewOr);
562 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000563 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000564 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000565 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000566 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000567 Value *NewAnd1 = Builder->CreateAnd(B, D);
568 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
569 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000570 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000571
572 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000573 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000574 // easy cases for now" decision.
575 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000576 if (!BCst)
577 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000578 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000579 if (!DCst)
580 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000581
Sanjay Patel77bf6222017-04-03 16:53:12 +0000582 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000583 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
584 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
585 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
586 // Only valid if one of the masks is a superset of the other (check "B&D" is
587 // the same as either B or D).
588 APInt NewMask = BCst->getValue() & DCst->getValue();
589
590 if (NewMask == BCst->getValue())
591 return LHS;
592 else if (NewMask == DCst->getValue())
593 return RHS;
594 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000595
596 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000597 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
598 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
599 // Only valid if one of the masks is a superset of the other (check "B|D" is
600 // the same as either B or D).
601 APInt NewMask = BCst->getValue() | DCst->getValue();
602
603 if (NewMask == BCst->getValue())
604 return LHS;
605 else if (NewMask == DCst->getValue())
606 return RHS;
607 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000608
609 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000610 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000611 // We already know that B & C == C && D & E == E.
612 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
613 // C and E, which are shared by both the mask B and the mask D, don't
614 // contradict, then we can transform to
615 // -> (icmp eq (A & (B|D)), (C|E))
616 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000617 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000618 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000619 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000620 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000621 if (!CCst)
622 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000623 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000624 if (!ECst)
625 return nullptr;
626 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000627 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000628 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000629 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000630
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000631 // If there is a conflict, we should actually return a false for the
632 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000633 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000634 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000635 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000636
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000637 Value *NewOr1 = Builder->CreateOr(B, D);
638 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
639 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
640 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000641 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000642
Craig Topperf40110f2014-04-25 05:29:35 +0000643 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000644}
645
Erik Ecksteind1817522014-12-03 10:39:15 +0000646/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
647/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
648/// If \p Inverted is true then the check is for the inverted range, e.g.
649/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
650Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
651 bool Inverted) {
652 // Check the lower range comparison, e.g. x >= 0
653 // InstCombine already ensured that if there is a constant it's on the RHS.
654 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
655 if (!RangeStart)
656 return nullptr;
657
658 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
659 Cmp0->getPredicate());
660
661 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
662 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
663 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
664 return nullptr;
665
666 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
667 Cmp1->getPredicate());
668
669 Value *Input = Cmp0->getOperand(0);
670 Value *RangeEnd;
671 if (Cmp1->getOperand(0) == Input) {
672 // For the upper range compare we have: icmp x, n
673 RangeEnd = Cmp1->getOperand(1);
674 } else if (Cmp1->getOperand(1) == Input) {
675 // For the upper range compare we have: icmp n, x
676 RangeEnd = Cmp1->getOperand(0);
677 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
678 } else {
679 return nullptr;
680 }
681
682 // Check the upper range comparison, e.g. x < n
683 ICmpInst::Predicate NewPred;
684 switch (Pred1) {
685 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
686 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
687 default: return nullptr;
688 }
689
690 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000691 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
692 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000693 return nullptr;
694
695 if (Inverted)
696 NewPred = ICmpInst::getInversePredicate(NewPred);
697
698 return Builder->CreateICmp(NewPred, Input, RangeEnd);
699}
700
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000701static Value *
702foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
703 bool JoinedByAnd,
704 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000705 Value *X = LHS->getOperand(0);
706 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000707 return nullptr;
708
Sanjay Patelef9f5862017-04-15 17:55:06 +0000709 const APInt *C1, *C2;
710 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
711 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000712 return nullptr;
713
714 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
715 ICmpInst::Predicate Pred = LHS->getPredicate();
716 if (Pred != RHS->getPredicate())
717 return nullptr;
718 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
719 return nullptr;
720 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
721 return nullptr;
722
723 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000724 if (C1->ugt(*C2))
725 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000726
Sanjay Patelef9f5862017-04-15 17:55:06 +0000727 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000728 if (Xor.isPowerOf2()) {
729 // If LHSC and RHSC differ by only one bit, then set that bit in X and
730 // compare against the larger constant:
731 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
732 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
733 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
734 // 'and' because that may lead to smaller codegen from a smaller constant.
735 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000736 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000737 }
738
739 // Special case: get the ordering right when the values wrap around zero.
740 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000741 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000742 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000743
Sanjay Patelef9f5862017-04-15 17:55:06 +0000744 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000745 // (X == 13 || X == 14) --> X - 13 <=u 1
746 // (X != 13 && X != 14) --> X - 13 >u 1
747 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000748 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000749 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
750 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
751 }
752
753 return nullptr;
754}
755
Craig Topperda6ea0d2017-06-16 05:10:37 +0000756// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
757// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
758Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
759 bool JoinedByAnd,
760 Instruction &CxtI) {
761 ICmpInst::Predicate Pred = LHS->getPredicate();
762 if (Pred != RHS->getPredicate())
763 return nullptr;
764 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
765 return nullptr;
766 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
767 return nullptr;
768
769 // TODO support vector splats
770 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
771 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
772 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
773 return nullptr;
774
775 Value *A, *B, *C, *D;
776 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
777 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
778 if (A == D || B == D)
779 std::swap(C, D);
780 if (B == C)
781 std::swap(A, B);
782
783 if (A == C &&
784 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
785 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
786 Value *Mask = Builder->CreateOr(B, D);
787 Value *Masked = Builder->CreateAnd(A, Mask);
788 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
789 return Builder->CreateICmp(NewPred, Masked, Mask);
790 }
791 }
792
793 return nullptr;
794}
795
Sanjay Patel18549272015-09-08 18:24:36 +0000796/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000797Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
798 Instruction &CxtI) {
799 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
800 // if K1 and K2 are a one-bit mask.
801 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
802 return V;
803
Sanjay Patel519a87a2017-04-05 17:38:34 +0000804 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000805
806 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000807 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000808 if (LHS->getOperand(0) == RHS->getOperand(1) &&
809 LHS->getOperand(1) == RHS->getOperand(0))
810 LHS->swapOperands();
811 if (LHS->getOperand(0) == RHS->getOperand(0) &&
812 LHS->getOperand(1) == RHS->getOperand(1)) {
813 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
814 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
815 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000816 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000817 }
818 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000819
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000820 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000821 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000822 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000823
Erik Ecksteind1817522014-12-03 10:39:15 +0000824 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
825 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
826 return V;
827
828 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
829 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
830 return V;
831
Sanjay Patelef9f5862017-04-15 17:55:06 +0000832 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
833 return V;
834
Chris Lattner0a8191e2010-01-05 07:50:36 +0000835 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000836 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000837 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
838 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
839 if (!LHSC || !RHSC)
840 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000841
Sanjay Patel519a87a2017-04-05 17:38:34 +0000842 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000843 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000844 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000845 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000846 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
847 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000848 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000849 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000850 }
851 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000852
Benjamin Kramer101720f2011-04-28 20:09:57 +0000853 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000854 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000855 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000856 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
857 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000858 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000859 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000860
861 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000862 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000863 if (match(RHS0, m_Trunc(m_Value(V))) &&
864 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000865 SmallC = RHSC;
866 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000867 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
868 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000869 SmallC = LHSC;
870 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000871 }
872
Sanjay Patel519a87a2017-04-05 17:38:34 +0000873 if (SmallC && BigC) {
874 unsigned BigBitSize = BigC->getType()->getBitWidth();
875 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000876
877 // Check that the low bits are zero.
878 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000879 if ((Low & AndC->getValue()).isNullValue() &&
880 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000881 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
882 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
883 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
884 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000885 }
886 }
887 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000888
Chris Lattner0a8191e2010-01-05 07:50:36 +0000889 // From here on, we only handle:
890 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000891 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000892 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000893
Sanjay Patel519a87a2017-04-05 17:38:34 +0000894 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
895 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
896 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
897 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
898 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000899 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000900
Chris Lattner0a8191e2010-01-05 07:50:36 +0000901 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000902 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000903 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000904
Chris Lattner0a8191e2010-01-05 07:50:36 +0000905 // Ensure that the larger constant is on the RHS.
906 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000907 if (CmpInst::isSigned(PredL) ||
908 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000909 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000910 else
911 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000912
Chris Lattner0a8191e2010-01-05 07:50:36 +0000913 if (ShouldSwap) {
914 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000915 std::swap(LHSC, RHSC);
916 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 }
918
Dan Gohman4a618822010-02-10 16:03:48 +0000919 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000920 // comparing a value against two constants and and'ing the result
921 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000922 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
923 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000925 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000926
Sanjay Patel519a87a2017-04-05 17:38:34 +0000927 switch (PredL) {
928 default:
929 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000931 switch (PredR) {
932 default:
933 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000935 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000936 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000937 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000938 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000939 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000940 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000941 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000942 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000943 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000944 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000946 // Potential folds for this case should already be handled.
947 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000948 }
949 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000950 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000951 switch (PredR) {
952 default:
953 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000954 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000955 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000956 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000957 break; // (X u> 13 & X != 15) -> no change
958 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000959 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
960 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000961 }
962 break;
963 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000964 switch (PredR) {
965 default:
966 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000968 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000969 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000970 break; // (X s> 13 & X != 15) -> no change
971 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000972 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000973 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000974 }
975 break;
976 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000977
Craig Topperf40110f2014-04-25 05:29:35 +0000978 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000979}
980
Sanjay Patel18549272015-09-08 18:24:36 +0000981/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
982/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000983Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000984 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
985 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
986 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
987
988 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
989 // Swap RHS operands to match LHS.
990 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
991 std::swap(Op1LHS, Op1RHS);
992 }
993
994 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
995 // Suppose the relation between x and y is R, where R is one of
996 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
997 // testing the desired relations.
998 //
999 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1000 // bool(R & CC0) && bool(R & CC1)
1001 // = bool((R & CC0) & (R & CC1))
1002 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1003 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1004 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1005 Builder);
1006
Chris Lattner0a8191e2010-01-05 07:50:36 +00001007 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1008 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001009 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001010 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001011
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1013 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1014 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1015 // If either of the constants are nans, then the whole thing returns
1016 // false.
1017 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001018 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001019 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001020 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001021
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 // Handle vector zeros. This occurs because the canonical form of
1023 // "fcmp ord x,x" is "fcmp ord x, 0".
1024 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1025 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001026 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001029
Craig Topperf40110f2014-04-25 05:29:35 +00001030 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001031}
1032
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001033/// Match De Morgan's Laws:
1034/// (~A & ~B) == (~(A | B))
1035/// (~A | ~B) == (~(A & B))
1036static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001037 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001038 auto Opcode = I.getOpcode();
1039 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1040 "Trying to match De Morgan's Laws with something other than and/or");
1041
Sanjay Patel7caaa792017-05-09 20:05:05 +00001042 // Flip the logic operation.
1043 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1044
1045 Value *A, *B;
1046 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1047 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1048 !IsFreeToInvert(A, A->hasOneUse()) &&
1049 !IsFreeToInvert(B, B->hasOneUse())) {
1050 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1051 return BinaryOperator::CreateNot(AndOr);
1052 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001053
1054 return nullptr;
1055}
1056
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001057bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1058 Value *CastSrc = CI->getOperand(0);
1059
1060 // Noop casts and casts of constants should be eliminated trivially.
1061 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1062 return false;
1063
1064 // If this cast is paired with another cast that can be eliminated, we prefer
1065 // to have it eliminated.
1066 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1067 if (isEliminableCastPair(PrecedingCI, CI))
1068 return false;
1069
1070 // If this is a vector sext from a compare, then we don't want to break the
1071 // idiom where each element of the extended vector is either zero or all ones.
1072 if (CI->getOpcode() == Instruction::SExt &&
1073 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1074 return false;
1075
1076 return true;
1077}
1078
Sanjay Patel60312bc42016-09-12 00:16:23 +00001079/// Fold {and,or,xor} (cast X), C.
1080static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1081 InstCombiner::BuilderTy *Builder) {
1082 Constant *C;
1083 if (!match(Logic.getOperand(1), m_Constant(C)))
1084 return nullptr;
1085
1086 auto LogicOpc = Logic.getOpcode();
1087 Type *DestTy = Logic.getType();
1088 Type *SrcTy = Cast->getSrcTy();
1089
Sanjay Pateld1e81192017-06-22 15:46:54 +00001090 // Move the logic operation ahead of a zext if the constant is unchanged in
1091 // the smaller source type. Performing the logic in a smaller type may provide
1092 // more information to later folds, and the smaller logic instruction may be
1093 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001094 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001095 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1096 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1097 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1098 if (ZextTruncC == C) {
1099 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1100 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1101 return new ZExtInst(NewOp, DestTy);
1102 }
1103 }
1104
1105 return nullptr;
1106}
1107
1108/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001109Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001110 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001111 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001112
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001114 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001115 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001116 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001117
Sanjay Patel9bba7502016-03-03 19:19:04 +00001118 // This must be a cast from an integer or integer vector source type to allow
1119 // transformation of the logic operation to the source type.
1120 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001121 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001122 if (!SrcTy->isIntOrIntVectorTy())
1123 return nullptr;
1124
Sanjay Patel60312bc42016-09-12 00:16:23 +00001125 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1126 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001127
Sanjay Patel9bba7502016-03-03 19:19:04 +00001128 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1129 if (!Cast1)
1130 return nullptr;
1131
1132 // Both operands of the logic operation are casts. The casts must be of the
1133 // same type for reduction.
1134 auto CastOpcode = Cast0->getOpcode();
1135 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001136 return nullptr;
1137
1138 Value *Cast0Src = Cast0->getOperand(0);
1139 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001140
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001141 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001142 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001143 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1144 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001145 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001146 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001147
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001148 // For now, only 'and'/'or' have optimizations after this.
1149 if (LogicOpc == Instruction::Xor)
1150 return nullptr;
1151
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001152 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001153 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001154 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1155 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1156 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001157 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001158 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001159 if (Res)
1160 return CastInst::Create(CastOpcode, Res, DestTy);
1161 return nullptr;
1162 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001163
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001164 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001165 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001166 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1167 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1168 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001169 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1170 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001171 if (Res)
1172 return CastInst::Create(CastOpcode, Res, DestTy);
1173 return nullptr;
1174 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001175
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001176 return nullptr;
1177}
1178
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001179static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1180 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1181
1182 // Canonicalize SExt or Not to the LHS
1183 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1184 std::swap(Op0, Op1);
1185 }
1186
1187 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1188 Value *X = nullptr;
1189 if (match(Op0, m_SExt(m_Value(X))) &&
1190 X->getType()->getScalarType()->isIntegerTy(1)) {
1191 Value *Zero = Constant::getNullValue(Op1->getType());
1192 return SelectInst::Create(X, Op1, Zero);
1193 }
1194
1195 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1196 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1197 X->getType()->getScalarType()->isIntegerTy(1)) {
1198 Value *Zero = Constant::getNullValue(Op0->getType());
1199 return SelectInst::Create(X, Zero, Op1);
1200 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001201
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001202 return nullptr;
1203}
1204
Sanjay Patele0c26e02017-04-23 22:00:02 +00001205static Instruction *foldAndToXor(BinaryOperator &I,
1206 InstCombiner::BuilderTy &Builder) {
1207 assert(I.getOpcode() == Instruction::And);
1208 Value *Op0 = I.getOperand(0);
1209 Value *Op1 = I.getOperand(1);
1210 Value *A, *B;
1211
1212 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1213 // (A | B) & ~(A & B) --> A ^ B
1214 // (A | B) & ~(B & A) --> A ^ B
1215 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1216 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1217 return BinaryOperator::CreateXor(A, B);
1218
1219 // (A | ~B) & (~A | B) --> ~(A ^ B)
1220 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1221 // (~B | A) & (~A | B) --> ~(A ^ B)
1222 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001223 if (Op0->hasOneUse() || Op1->hasOneUse())
1224 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1225 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1226 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001227
1228 return nullptr;
1229}
1230
1231static Instruction *foldOrToXor(BinaryOperator &I,
1232 InstCombiner::BuilderTy &Builder) {
1233 assert(I.getOpcode() == Instruction::Or);
1234 Value *Op0 = I.getOperand(0);
1235 Value *Op1 = I.getOperand(1);
1236 Value *A, *B;
1237
1238 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1239 // (A & B) | ~(A | B) --> ~(A ^ B)
1240 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001241 if (Op0->hasOneUse() || Op1->hasOneUse())
1242 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1243 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1244 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001245
1246 // (A & ~B) | (~A & B) --> A ^ B
1247 // (A & ~B) | (B & ~A) --> A ^ B
1248 // (~B & A) | (~A & B) --> A ^ B
1249 // (~B & A) | (B & ~A) --> A ^ B
1250 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1251 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1252 return BinaryOperator::CreateXor(A, B);
1253
1254 return nullptr;
1255}
1256
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001257// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1258// here. We should standardize that construct where it is needed or choose some
1259// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001260Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001261 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1263
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001264 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001265 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001266
Craig Toppera4205622017-06-09 03:21:29 +00001267 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001268 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001269
Craig Topper9d4171a2012-12-20 07:09:41 +00001270 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001271 // purpose is to compute bits we don't care about.
1272 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001273 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001274
Sanjay Patele0c26e02017-04-23 22:00:02 +00001275 // Do this before using distributive laws to catch simple and/or/not patterns.
1276 if (Instruction *Xor = foldAndToXor(I, *Builder))
1277 return Xor;
1278
1279 // (A|B)&(A|C) -> A|(B&C) etc
1280 if (Value *V = SimplifyUsingDistributiveLaws(I))
1281 return replaceInstUsesWith(I, V);
1282
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001283 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001284 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001285
Chris Lattner0a8191e2010-01-05 07:50:36 +00001286 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1287 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288
1289 // Optimize a variety of ((val OP C1) & C2) combinations...
1290 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1291 Value *Op0LHS = Op0I->getOperand(0);
1292 Value *Op0RHS = Op0I->getOperand(1);
1293 switch (Op0I->getOpcode()) {
1294 default: break;
1295 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001296 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001297 // If the mask is only needed on one incoming arm, push it up.
1298 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001299
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001300 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001301 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001302 // Not masking anything out for the LHS, move to RHS.
1303 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1304 Op0RHS->getName()+".masked");
1305 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1306 }
1307 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001308 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001309 // Not masking anything out for the RHS, move to LHS.
1310 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1311 Op0LHS->getName()+".masked");
1312 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1313 }
1314
1315 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001316 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001317 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001318 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001319 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001320 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1321
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322 break;
1323
1324 case Instruction::Shl:
1325 case Instruction::LShr:
1326 // (1 << x) & 1 --> zext(x == 0)
1327 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001328 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001329 Value *NewICmp =
1330 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1331 return new ZExtInst(NewICmp, I.getType());
1332 }
1333 break;
1334 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001335
David Majnemerde55c602017-01-17 18:08:06 +00001336 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1337 // of X and OP behaves well when given trunc(C1) and X.
1338 switch (Op0I->getOpcode()) {
1339 default:
1340 break;
1341 case Instruction::Xor:
1342 case Instruction::Or:
1343 case Instruction::Mul:
1344 case Instruction::Add:
1345 case Instruction::Sub:
1346 Value *X;
1347 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001348 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001349 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1350 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1351 Value *BinOp;
1352 if (isa<ZExtInst>(Op0LHS))
1353 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1354 else
1355 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1356 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1357 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1358 return new ZExtInst(And, I.getType());
1359 }
1360 }
1361 }
1362
Chris Lattner0a8191e2010-01-05 07:50:36 +00001363 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1364 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1365 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001366 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001367
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001368 // If this is an integer truncation, and if the source is an 'and' with
1369 // immediate, transform it. This frequently occurs for bitfield accesses.
1370 {
Craig Topperf40110f2014-04-25 05:29:35 +00001371 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001372 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1373 // Change: and (trunc (and X, YC) to T), C2
1374 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001375 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001376 // other simplifications.
1377 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1378 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1379 C3 = ConstantExpr::getAnd(C3, AndRHS);
1380 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001381 }
1382 }
Craig Topper86173602017-04-04 20:26:25 +00001383 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001384
Craig Topper86173602017-04-04 20:26:25 +00001385 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001386 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1387 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001388
Sanjay Patel7caaa792017-05-09 20:05:05 +00001389 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001390 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001391
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001393 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001394 // A&(A^B) => A & ~B
1395 {
1396 Value *tmpOp0 = Op0;
1397 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001398 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001399 if (A == Op1 || B == Op1 ) {
1400 tmpOp1 = Op0;
1401 tmpOp0 = Op1;
1402 // Simplify below
1403 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001404 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001406 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001407 if (B == tmpOp0) {
1408 std::swap(A, B);
1409 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001410 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001411 // A is originally -1 (or a vector of -1 and undefs), then we enter
1412 // an endless loop. By checking that A is non-constant we ensure that
1413 // we will never get to the loop.
1414 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001415 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001416 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001417 }
1418
1419 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001420 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001421 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001422 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001423 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001424
1425 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1426 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1427 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001428 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001429 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1430
1431 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1432 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1433 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001434 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001435 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001436
1437 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001438 // (A | B) & (B ^ (~A)) -> (A & B)
1439 // (B | A) & ((~A) ^ B) -> (A & B)
1440 // (B | A) & (B ^ (~A)) -> (A & B)
1441 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1442 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001443 return BinaryOperator::CreateAnd(A, B);
1444
1445 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001446 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001447 // (B ^ (~A)) & (A | B) -> (A & B)
1448 // (B ^ (~A)) & (B | A) -> (A & B)
1449 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001450 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001451 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001452 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001453
David Majnemer5e96f1b2014-08-30 06:18:20 +00001454 {
1455 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1456 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1457 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001458 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001459 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001460
David Majnemer5e96f1b2014-08-30 06:18:20 +00001461 // TODO: Make this recursive; it's a little tricky because an arbitrary
1462 // number of 'and' instructions might have to be created.
1463 Value *X, *Y;
1464 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1465 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001466 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001467 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001468 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001469 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001470 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001471 }
1472 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1473 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001474 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001475 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001476 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001477 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001478 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001479 }
1480 }
1481
Chris Lattner4e8137d2010-02-11 06:26:33 +00001482 // If and'ing two fcmp, try combine them into one.
1483 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1484 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001485 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001486 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001487
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001488 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1489 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001490
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001491 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1492 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001493
Craig Topperf40110f2014-04-25 05:29:35 +00001494 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001495}
1496
Chad Rosiera00df492016-05-25 16:22:14 +00001497/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1498/// insert the new intrinsic and return it.
1499Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1501
1502 // Look through zero extends.
1503 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1504 Op0 = Ext->getOperand(0);
1505
1506 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1507 Op1 = Ext->getOperand(0);
1508
1509 // (A | B) | C and A | (B | C) -> bswap if possible.
1510 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1511 match(Op1, m_Or(m_Value(), m_Value()));
1512
1513 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1514 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1515 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1516
1517 // (A & B) | (C & D) -> bswap if possible.
1518 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1519 match(Op1, m_And(m_Value(), m_Value()));
1520
1521 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1522 return nullptr;
1523
James Molloyf01488e2016-01-15 09:20:19 +00001524 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001525 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001526 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001527 Instruction *LastInst = Insts.pop_back_val();
1528 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001529
James Molloyf01488e2016-01-15 09:20:19 +00001530 for (auto *Inst : Insts)
1531 Worklist.Add(Inst);
1532 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001533}
1534
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001535/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1536static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1537 unsigned NumElts = C1->getType()->getVectorNumElements();
1538 for (unsigned i = 0; i != NumElts; ++i) {
1539 Constant *EltC1 = C1->getAggregateElement(i);
1540 Constant *EltC2 = C2->getAggregateElement(i);
1541 if (!EltC1 || !EltC2)
1542 return false;
1543
1544 // One element must be all ones, and the other must be all zeros.
1545 // FIXME: Allow undef elements.
1546 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1547 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1548 return false;
1549 }
1550 return true;
1551}
1552
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001553/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1554/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1555/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001556static Value *getSelectCondition(Value *A, Value *B,
1557 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001558 // If these are scalars or vectors of i1, A can be used directly.
1559 Type *Ty = A->getType();
1560 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1561 return A;
1562
1563 // If A and B are sign-extended, look through the sexts to find the booleans.
1564 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001565 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001566 if (match(A, m_SExt(m_Value(Cond))) &&
1567 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001568 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1569 NotB = peekThroughBitcast(NotB, true);
1570 if (match(NotB, m_SExt(m_Specific(Cond))))
1571 return Cond;
1572 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001573
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001574 // All scalar (and most vector) possibilities should be handled now.
1575 // Try more matches that only apply to non-splat constant vectors.
1576 if (!Ty->isVectorTy())
1577 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001578
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001579 // If both operands are constants, see if the constants are inverse bitmasks.
1580 Constant *AC, *BC;
1581 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1582 areInverseVectorBitmasks(AC, BC))
1583 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1584
1585 // If both operands are xor'd with constants using the same sexted boolean
1586 // operand, see if the constants are inverse bitmasks.
1587 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1588 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1589 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1590 areInverseVectorBitmasks(AC, BC)) {
1591 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1592 return Builder.CreateXor(Cond, AC);
1593 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001594 return nullptr;
1595}
1596
1597/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1598/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001599static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001600 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001601 // The potential condition of the select may be bitcasted. In that case, look
1602 // through its bitcast and the corresponding bitcast of the 'not' condition.
1603 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001604 A = peekThroughBitcast(A, true);
1605 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001606
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001607 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001608 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001609 // The bitcasts will either all exist or all not exist. The builder will
1610 // not create unnecessary casts if the types already match.
1611 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1612 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1613 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1614 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001615 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001616
Craig Topperf40110f2014-04-25 05:29:35 +00001617 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001618}
1619
Sanjay Patel18549272015-09-08 18:24:36 +00001620/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001621Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001622 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001623 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1624 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001625 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1626 return V;
1627
1628 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1629
Sanjay Patel519a87a2017-04-05 17:38:34 +00001630 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1631 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001632
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001633 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1634 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1635 // The original condition actually refers to the following two ranges:
1636 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1637 // We can fold these two ranges if:
1638 // 1) C1 and C2 is unsigned greater than C3.
1639 // 2) The two ranges are separated.
1640 // 3) C1 ^ C2 is one-bit mask.
1641 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1642 // This implies all values in the two ranges differ by exactly one bit.
1643
Sanjay Patel519a87a2017-04-05 17:38:34 +00001644 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1645 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1646 LHSC->getType() == RHSC->getType() &&
1647 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001648
1649 Value *LAdd = LHS->getOperand(0);
1650 Value *RAdd = RHS->getOperand(0);
1651
1652 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001653 ConstantInt *LAddC, *RAddC;
1654 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1655 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1656 LAddC->getValue().ugt(LHSC->getValue()) &&
1657 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001658
Sanjay Patel519a87a2017-04-05 17:38:34 +00001659 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1660 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1661 ConstantInt *MaxAddC = nullptr;
1662 if (LAddC->getValue().ult(RAddC->getValue()))
1663 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001664 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001665 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001666
Sanjay Patel519a87a2017-04-05 17:38:34 +00001667 APInt RRangeLow = -RAddC->getValue();
1668 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1669 APInt LRangeLow = -LAddC->getValue();
1670 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001671 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1672 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1673 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1674 : RRangeLow - LRangeLow;
1675
1676 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001677 RangeDiff.ugt(LHSC->getValue())) {
1678 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001679
Sanjay Patel519a87a2017-04-05 17:38:34 +00001680 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1681 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1682 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001683 }
1684 }
1685 }
1686 }
1687
Chris Lattner0a8191e2010-01-05 07:50:36 +00001688 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001689 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001690 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1691 LHS->getOperand(1) == RHS->getOperand(0))
1692 LHS->swapOperands();
1693 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1694 LHS->getOperand(1) == RHS->getOperand(1)) {
1695 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1696 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1697 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001698 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001699 }
1700 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001701
1702 // handle (roughly):
1703 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001704 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001705 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001706
Sanjay Patele4159d22017-04-10 19:38:36 +00001707 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001708 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1709 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1710 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001711 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001712 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001713 B = LHS0;
1714 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1715 A = RHS0;
1716 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001717 A = RHS->getOperand(1);
1718 }
1719 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1720 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001721 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001722 B = RHS0;
1723 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1724 A = LHS0;
1725 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001726 A = LHS->getOperand(1);
1727 }
1728 if (A && B)
1729 return Builder->CreateICmp(
1730 ICmpInst::ICMP_UGE,
1731 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1732 }
1733
Erik Ecksteind1817522014-12-03 10:39:15 +00001734 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1735 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1736 return V;
1737
1738 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1739 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1740 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001741
Sanjay Patelef9f5862017-04-15 17:55:06 +00001742 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1743 return V;
1744
David Majnemerc2a990b2013-07-05 00:31:17 +00001745 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001746 if (!LHSC || !RHSC)
1747 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001748
Sanjay Patel519a87a2017-04-05 17:38:34 +00001749 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001750 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001751 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001752 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001753 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001754 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001755 }
1756
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001757 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001758 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001759 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1760 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001761 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001762 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001763 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001764 }
1765
Chris Lattner0a8191e2010-01-05 07:50:36 +00001766 // From here on, we only handle:
1767 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001768 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001769 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001770
Sanjay Patel519a87a2017-04-05 17:38:34 +00001771 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1772 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1773 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1774 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1775 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001776 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001777
Chris Lattner0a8191e2010-01-05 07:50:36 +00001778 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001779 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001780 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001781
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 // Ensure that the larger constant is on the RHS.
1783 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001784 if (CmpInst::isSigned(PredL) ||
1785 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001786 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001787 else
1788 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001789
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 if (ShouldSwap) {
1791 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001792 std::swap(LHSC, RHSC);
1793 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001795
Dan Gohman4a618822010-02-10 16:03:48 +00001796 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001797 // comparing a value against two constants and or'ing the result
1798 // together. Because of the above check, we know that we only have
1799 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1800 // icmp folding check above), that the two constants are not
1801 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001802 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001803
Sanjay Patel519a87a2017-04-05 17:38:34 +00001804 switch (PredL) {
1805 default:
1806 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001807 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001808 switch (PredR) {
1809 default:
1810 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001812 // Potential folds for this case should already be handled.
1813 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001814 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1815 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 }
1818 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001820 switch (PredR) {
1821 default:
1822 llvm_unreachable("Unknown integer condition code!");
1823 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001824 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001825 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001826 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001827 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1828 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829 }
1830 break;
1831 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001832 switch (PredR) {
1833 default:
1834 llvm_unreachable("Unknown integer condition code!");
1835 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001837 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001838 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001839 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001840 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001841 }
1842 break;
1843 }
Craig Topperf40110f2014-04-25 05:29:35 +00001844 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001845}
1846
Sanjay Patel18549272015-09-08 18:24:36 +00001847/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1848/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001849Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001850 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1851 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1852 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1853
1854 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1855 // Swap RHS operands to match LHS.
1856 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1857 std::swap(Op1LHS, Op1RHS);
1858 }
1859
1860 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1861 // This is a similar transformation to the one in FoldAndOfFCmps.
1862 //
1863 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1864 // bool(R & CC0) || bool(R & CC1)
1865 // = bool((R & CC0) | (R & CC1))
1866 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1867 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1868 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1869 Builder);
1870
Chris Lattner0a8191e2010-01-05 07:50:36 +00001871 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001872 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001873 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1874 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1875 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1876 // If either of the constants are nans, then the whole thing returns
1877 // true.
1878 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001879 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001880
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881 // Otherwise, no need to compare the two constants, compare the
1882 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001883 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001884 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001885
Chris Lattner0a8191e2010-01-05 07:50:36 +00001886 // Handle vector zeros. This occurs because the canonical form of
1887 // "fcmp uno x,x" is "fcmp uno x, 0".
1888 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1889 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001890 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001891
Craig Topperf40110f2014-04-25 05:29:35 +00001892 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001893 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001894
Craig Topperf40110f2014-04-25 05:29:35 +00001895 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001896}
1897
Sanjay Patel18549272015-09-08 18:24:36 +00001898/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001899///
1900/// ((A | B) & C1) | (B & C2)
1901///
1902/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001903///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001904/// (A & C1) | B
1905///
1906/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001907static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1908 Value *A, Value *B, Value *C,
1909 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001911 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001912
Craig Topperf40110f2014-04-25 05:29:35 +00001913 Value *V1 = nullptr;
1914 ConstantInt *CI2 = nullptr;
1915 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001916
1917 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001918 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001919
1920 if (V1 == A || V1 == B) {
1921 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1922 return BinaryOperator::CreateOr(NewOp, V1);
1923 }
1924
Craig Topperf40110f2014-04-25 05:29:35 +00001925 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926}
1927
David Majnemer5d1aeba2014-08-21 05:14:48 +00001928/// \brief This helper function folds:
1929///
Craig Toppera074c102017-06-21 18:57:00 +00001930/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001931///
1932/// into:
1933///
1934/// (A & C1) ^ B
1935///
1936/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001937static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1938 Value *A, Value *B, Value *C,
1939 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001940 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1941 if (!CI1)
1942 return nullptr;
1943
1944 Value *V1 = nullptr;
1945 ConstantInt *CI2 = nullptr;
1946 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1947 return nullptr;
1948
1949 APInt Xor = CI1->getValue() ^ CI2->getValue();
1950 if (!Xor.isAllOnesValue())
1951 return nullptr;
1952
1953 if (V1 == A || V1 == B) {
1954 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1955 return BinaryOperator::CreateXor(NewOp, V1);
1956 }
1957
1958 return nullptr;
1959}
1960
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001961// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1962// here. We should standardize that construct where it is needed or choose some
1963// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001965 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1967
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001968 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001969 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001970
Craig Toppera4205622017-06-09 03:21:29 +00001971 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001972 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001973
Craig Topper9d4171a2012-12-20 07:09:41 +00001974 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001975 // purpose is to compute bits we don't care about.
1976 if (SimplifyDemandedInstructionBits(I))
1977 return &I;
1978
Sanjay Patele0c26e02017-04-23 22:00:02 +00001979 // Do this before using distributive laws to catch simple and/or/not patterns.
1980 if (Instruction *Xor = foldOrToXor(I, *Builder))
1981 return Xor;
1982
1983 // (A&B)|(A&C) -> A&(B|C) etc
1984 if (Value *V = SimplifyUsingDistributiveLaws(I))
1985 return replaceInstUsesWith(I, V);
1986
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001987 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001988 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001989
Craig Topper86173602017-04-04 20:26:25 +00001990 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001991 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1992 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001993
Chad Rosiere5819e22016-05-26 14:58:51 +00001994 // Given an OR instruction, check to see if this is a bswap.
1995 if (Instruction *BSwap = MatchBSwap(I))
1996 return BSwap;
1997
Craig Topperafa07c52017-04-09 06:12:41 +00001998 {
1999 Value *A;
2000 const APInt *C;
2001 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2002 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2003 MaskedValueIsZero(Op1, *C, 0, &I)) {
2004 Value *NOr = Builder->CreateOr(A, Op1);
2005 NOr->takeName(Op0);
2006 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002007 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002008 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002009
Craig Topperafa07c52017-04-09 06:12:41 +00002010 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2011 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2012 MaskedValueIsZero(Op0, *C, 0, &I)) {
2013 Value *NOr = Builder->CreateOr(A, Op0);
2014 NOr->takeName(Op0);
2015 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002016 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002017 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002018 }
2019
Craig Topperafa07c52017-04-09 06:12:41 +00002020 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002021
Suyog Sardad64faf62014-07-22 18:09:41 +00002022 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002023 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2024 return BinaryOperator::CreateOr(A, Op1);
2025 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2026 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002027
2028 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002029 // The NOT is guaranteed to be in the RHS by complexity ordering.
2030 if (match(Op1, m_Not(m_Value(A))) &&
2031 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2032 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002033
Chris Lattner0a8191e2010-01-05 07:50:36 +00002034 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002035 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002036 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2037 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002038 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002039 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2040 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002042 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002043 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002044 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002045 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002046 ((V1 == B &&
2047 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2048 (V2 == B &&
2049 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002050 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002051 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002052 // Or commutes, try both ways.
2053 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002054 ((V1 == A &&
2055 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2056 (V2 == A &&
2057 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002058 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002059 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002060
Chris Lattner95188692010-01-11 06:55:24 +00002061 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002062 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002063 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002064 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002065 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002066 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002067 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002068 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2069 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002070 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002071 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002072 }
2073 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002074
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002075 // Don't try to form a select if it's unlikely that we'll get rid of at
2076 // least one of the operands. A select is generally more expensive than the
2077 // 'or' that it is replacing.
2078 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2079 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2080 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2081 return replaceInstUsesWith(I, V);
2082 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2083 return replaceInstUsesWith(I, V);
2084 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2085 return replaceInstUsesWith(I, V);
2086 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2087 return replaceInstUsesWith(I, V);
2088 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2089 return replaceInstUsesWith(I, V);
2090 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097
Benjamin Kramer11743242010-07-12 13:34:22 +00002098 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002099 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2100 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2101 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002102 }
2103 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002104 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2105 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2106 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002107 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002108 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002109 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2110 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2111 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002112 }
2113 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002114 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2115 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2116 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002117 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002118 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002119
David Majnemer42af3602014-07-30 21:26:37 +00002120 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2121 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2122 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002123 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002124
2125 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2126 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2127 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002128 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002129
David Majnemerf1eda232014-08-14 06:41:38 +00002130 // ((B | C) & A) | B -> B | (A & C)
2131 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2132 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2133
Sanjay Patel7caaa792017-05-09 20:05:05 +00002134 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002135 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002136
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002137 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002138 bool SwappedForXor = false;
2139 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002140 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002141 SwappedForXor = true;
2142 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002143
2144 // A | ( A ^ B) -> A | B
2145 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002146 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002147 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2148 if (Op0 == A || Op0 == B)
2149 return BinaryOperator::CreateOr(A, B);
2150
Chad Rosier7813dce2012-04-26 23:29:14 +00002151 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2152 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2153 return BinaryOperator::CreateOr(A, B);
2154
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002155 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2156 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2157 return BinaryOperator::CreateOr(Not, Op0);
2158 }
2159 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2160 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2161 return BinaryOperator::CreateOr(Not, Op0);
2162 }
2163 }
2164
2165 // A | ~(A | B) -> A | ~B
2166 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002167 if (match(Op1, m_Not(m_Value(A))))
2168 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002169 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2170 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2171 B->getOpcode() == Instruction::Xor)) {
2172 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2173 B->getOperand(0);
2174 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2175 return BinaryOperator::CreateOr(Not, Op0);
2176 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002177
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002178 // (A & B) | (~A ^ B) -> (~A ^ B)
2179 // (A & B) | (B ^ ~A) -> (~A ^ B)
2180 // (B & A) | (~A ^ B) -> (~A ^ B)
2181 // (B & A) | (B ^ ~A) -> (~A ^ B)
2182 // The match order is important: match the xor first because the 'not'
2183 // operation defines 'A'. We do not need to match the xor as Op0 because the
2184 // xor was canonicalized to Op1 above.
2185 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2186 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002187 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2188
Eli Friedmane06535b2012-03-16 00:52:42 +00002189 if (SwappedForXor)
2190 std::swap(Op0, Op1);
2191
David Majnemer3d6f80b2014-11-28 19:58:29 +00002192 {
2193 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2194 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2195 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002196 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002197 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002198
David Majnemer3d6f80b2014-11-28 19:58:29 +00002199 // TODO: Make this recursive; it's a little tricky because an arbitrary
2200 // number of 'or' instructions might have to be created.
2201 Value *X, *Y;
2202 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2203 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002204 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002205 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002206 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002207 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002208 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002209 }
2210 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2211 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002212 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002213 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002214 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002215 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002216 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002217 }
2218 }
2219
Chris Lattner4e8137d2010-02-11 06:26:33 +00002220 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2221 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2222 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002223 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002224 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002225
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002226 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2227 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002228
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002229 // 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 +00002230 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002231 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002232 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002233 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002234 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002235 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2236
Owen Andersonc237a842010-09-13 17:59:27 +00002237 // Note: If we've gotten to the point of visiting the outer OR, then the
2238 // inner one couldn't be simplified. If it was a constant, then it won't
2239 // be simplified by a later pass either, so we try swapping the inner/outer
2240 // ORs in the hopes that we'll be able to simplify it this way.
2241 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002242 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002243 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2244 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2245 Value *Inner = Builder->CreateOr(A, Op1);
2246 Inner->takeName(Op0);
2247 return BinaryOperator::CreateOr(Inner, C1);
2248 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002249
Bill Wendling23242092013-02-16 23:41:36 +00002250 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2251 // Since this OR statement hasn't been optimized further yet, we hope
2252 // that this transformation will allow the new ORs to be optimized.
2253 {
Craig Topperf40110f2014-04-25 05:29:35 +00002254 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002255 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2256 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2257 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2258 Value *orTrue = Builder->CreateOr(A, C);
2259 Value *orFalse = Builder->CreateOr(B, D);
2260 return SelectInst::Create(X, orTrue, orFalse);
2261 }
2262 }
2263
Craig Topperf40110f2014-04-25 05:29:35 +00002264 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002265}
2266
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002267/// A ^ B can be specified using other logic ops in a variety of patterns. We
2268/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002269static Instruction *foldXorToXor(BinaryOperator &I,
2270 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002271 assert(I.getOpcode() == Instruction::Xor);
2272 Value *Op0 = I.getOperand(0);
2273 Value *Op1 = I.getOperand(1);
2274 Value *A, *B;
2275
2276 // There are 4 commuted variants for each of the basic patterns.
2277
2278 // (A & B) ^ (A | B) -> A ^ B
2279 // (A & B) ^ (B | A) -> A ^ B
2280 // (A | B) ^ (A & B) -> A ^ B
2281 // (A | B) ^ (B & A) -> A ^ B
2282 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2283 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2284 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2285 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2286 I.setOperand(0, A);
2287 I.setOperand(1, B);
2288 return &I;
2289 }
2290
2291 // (A | ~B) ^ (~A | B) -> A ^ B
2292 // (~B | A) ^ (~A | B) -> A ^ B
2293 // (~A | B) ^ (A | ~B) -> A ^ B
2294 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002295 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2296 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2297 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2298 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002299 I.setOperand(0, A);
2300 I.setOperand(1, B);
2301 return &I;
2302 }
2303
2304 // (A & ~B) ^ (~A & B) -> A ^ B
2305 // (~B & A) ^ (~A & B) -> A ^ B
2306 // (~A & B) ^ (A & ~B) -> A ^ B
2307 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002308 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2309 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2310 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2311 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002312 I.setOperand(0, A);
2313 I.setOperand(1, B);
2314 return &I;
2315 }
2316
Craig Topperf60ab472017-07-02 01:15:51 +00002317 // For the remaining cases we need to get rid of one of the operands.
2318 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2319 return nullptr;
2320
2321 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2322 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2323 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2324 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2325 // Complexity sorting ensures the not will be on the right side.
2326 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2327 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2328 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2329 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2330 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2331
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002332 return nullptr;
2333}
2334
Sanjay Patel5e456b92017-05-18 20:53:16 +00002335Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2336 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2337 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2338 LHS->getOperand(1) == RHS->getOperand(0))
2339 LHS->swapOperands();
2340 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2341 LHS->getOperand(1) == RHS->getOperand(1)) {
2342 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2343 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2344 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2345 bool isSigned = LHS->isSigned() || RHS->isSigned();
2346 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2347 }
2348 }
2349
Sanjay Pateladca8252017-06-20 12:40:55 +00002350 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2351 // into those logic ops. That is, try to turn this into an and-of-icmps
2352 // because we have many folds for that pattern.
2353 //
2354 // This is based on a truth table definition of xor:
2355 // X ^ Y --> (X | Y) & !(X & Y)
2356 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2357 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2358 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2359 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2360 // TODO: Independently handle cases where the 'and' side is a constant.
2361 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2362 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2363 RHS->setPredicate(RHS->getInversePredicate());
2364 return Builder->CreateAnd(LHS, RHS);
2365 }
2366 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002367 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002368 LHS->setPredicate(LHS->getInversePredicate());
2369 return Builder->CreateAnd(LHS, RHS);
2370 }
2371 }
2372 }
2373
Sanjay Patel5e456b92017-05-18 20:53:16 +00002374 return nullptr;
2375}
2376
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002377// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2378// here. We should standardize that construct where it is needed or choose some
2379// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002380Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002381 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2383
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002384 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002385 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002386
Craig Toppera4205622017-06-09 03:21:29 +00002387 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002389
Craig Topperf60ab472017-07-02 01:15:51 +00002390 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002391 return NewXor;
2392
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002393 // (A&B)^(A&C) -> A&(B^C) etc
2394 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002395 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002396
Craig Topper9d4171a2012-12-20 07:09:41 +00002397 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002398 // purpose is to compute bits we don't care about.
2399 if (SimplifyDemandedInstructionBits(I))
2400 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002401
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002402 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002403 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002404
Sanjay Patel6381db12017-05-02 15:31:40 +00002405 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2406 Value *X, *Y;
2407
2408 // We must eliminate the and/or (one-use) for these transforms to not increase
2409 // the instruction count.
2410 // ~(~X & Y) --> (X | ~Y)
2411 // ~(Y & ~X) --> (X | ~Y)
2412 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2413 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2414 return BinaryOperator::CreateOr(X, NotY);
2415 }
2416 // ~(~X | Y) --> (X & ~Y)
2417 // ~(Y | ~X) --> (X & ~Y)
2418 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2419 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2420 return BinaryOperator::CreateAnd(X, NotY);
2421 }
2422
Sanjay Patel3b863f82017-04-22 18:05:35 +00002423 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002424 BinaryOperator *NotVal;
2425 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2426 if (NotVal->getOpcode() == Instruction::And ||
2427 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002428 // Apply DeMorgan's Law when inverts are free:
2429 // ~(X & Y) --> (~X | ~Y)
2430 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002431 if (IsFreeToInvert(NotVal->getOperand(0),
2432 NotVal->getOperand(0)->hasOneUse()) &&
2433 IsFreeToInvert(NotVal->getOperand(1),
2434 NotVal->getOperand(1)->hasOneUse())) {
2435 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2436 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2437 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002438 return BinaryOperator::CreateOr(NotX, NotY);
2439 return BinaryOperator::CreateAnd(NotX, NotY);
2440 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002441 }
2442
2443 // ~(~X >>s Y) --> (X >>s Y)
2444 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2445 return BinaryOperator::CreateAShr(X, Y);
2446
2447 // If we are inverting a right-shifted constant, we may be able to eliminate
2448 // the 'not' by inverting the constant and using the opposite shift type.
2449 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2450 // but we must check that in case that transform has not fired yet.
2451 const APInt *C;
2452 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2453 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2454 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2455 return BinaryOperator::CreateLShr(NotC, Y);
2456 }
2457
2458 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2459 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2460 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2461 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002462 }
2463 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002464
Craig Topper798a19a2017-06-29 00:07:08 +00002465 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002466 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002467 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002468 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2469 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002470 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002471
Craig Topper9d1821b2017-04-09 06:12:31 +00002472 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002473 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2474 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2475 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2476 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2477 Instruction::CastOps Opcode = Op0C->getOpcode();
2478 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002479 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002480 Op0C->getDestTy()))) {
2481 CI->setPredicate(CI->getInversePredicate());
2482 return CastInst::Create(Opcode, CI, Op0C->getType());
2483 }
2484 }
2485 }
2486 }
2487
2488 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2489 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002490 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002491 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2492 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002493 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2494 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002495 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002496
Chris Lattner0a8191e2010-01-05 07:50:36 +00002497 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2498 if (Op0I->getOpcode() == Instruction::Add) {
2499 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002500 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002501 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002502 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2503 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002504 } else if (RHSC->getValue().isSignMask()) {
2505 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002506 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002507 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2508
2509 }
2510 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002511 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002512 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2513 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002514 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515 // Anything in both C1 and C2 is known to be zero, remove it from
2516 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002517 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002518 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002519 ConstantExpr::getNot(CommonBits));
2520 Worklist.Add(Op0I);
2521 I.setOperand(0, Op0I->getOperand(0));
2522 I.setOperand(1, NewRHS);
2523 return &I;
2524 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002525 } else if (Op0I->getOpcode() == Instruction::LShr) {
2526 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2527 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002528 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002529 ConstantInt *C1;
2530 if (Op0I->hasOneUse() &&
2531 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2532 E1->getOpcode() == Instruction::Xor &&
2533 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2534 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002535 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002536 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2537 FoldConst ^= C3->getValue();
2538 // Prepare the two operands.
2539 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2540 Opnd0->takeName(Op0I);
2541 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2542 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2543
2544 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2545 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002546 }
2547 }
2548 }
Craig Topper86173602017-04-04 20:26:25 +00002549 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002550
Craig Topper86173602017-04-04 20:26:25 +00002551 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002552 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2553 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554
Craig Topper76394602017-04-10 06:53:23 +00002555 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002556 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002557 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002558 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002559 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002560 std::swap(A, B);
2561 }
2562 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002563 I.swapOperands(); // Simplified below.
2564 std::swap(Op0, Op1);
2565 }
Craig Topper76394602017-04-10 06:53:23 +00002566 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002567 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002568 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002569 std::swap(A, B);
2570 }
2571 if (B == Op0) { // A^(B&A) -> (B&A)^A
2572 I.swapOperands(); // Simplified below.
2573 std::swap(Op0, Op1);
2574 }
2575 }
2576 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002577
Craig Topper76394602017-04-10 06:53:23 +00002578 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002579 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002580 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002581 if (A == Op1) // (B|A)^B == (A|B)^B
2582 std::swap(A, B);
2583 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002584 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002585 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002586 if (A == Op1) // (A&B)^A -> (B&A)^A
2587 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002588 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002589 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002590 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002591 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002592 }
2593 }
2594 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002595
Craig Topper76394602017-04-10 06:53:23 +00002596 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002597 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002598 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002599 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2600 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002601 if (D == A)
2602 return BinaryOperator::CreateXor(
2603 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2604 if (D == B)
2605 return BinaryOperator::CreateXor(
2606 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002607 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002608 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002609 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2610 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002611 if (D == A)
2612 return BinaryOperator::CreateXor(
2613 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2614 if (D == B)
2615 return BinaryOperator::CreateXor(
2616 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002617 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002618 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002619 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002620 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002621 return BinaryOperator::CreateOr(A, B);
2622 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002623 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002624 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002625 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002626 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002627
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002628 // (A & ~B) ^ ~A -> ~(A & B)
2629 // (~B & A) ^ ~A -> ~(A & B)
2630 Value *A, *B;
2631 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002632 match(Op1, m_Not(m_Specific(A))))
2633 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2634
Sanjay Patel5e456b92017-05-18 20:53:16 +00002635 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2636 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2637 if (Value *V = foldXorOfICmps(LHS, RHS))
2638 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002639
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002640 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2641 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002642
Craig Topperf40110f2014-04-25 05:29:35 +00002643 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002644}