blob: cb3f3214e99c69adfde553d503f5b8a59f2ea8b4 [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
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000085 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
86
87 // Can't do vectors.
Sanjay Patel1e6ca442016-11-22 22:54:36 +000088 if (I.getType()->isVectorTy())
89 return nullptr;
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000090
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000091 Value *OldLHS = I.getOperand(0);
92 Value *OldRHS = I.getOperand(1);
93 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
94 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
95 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
96 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
97 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
98 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
99
100 if (!IsBswapLHS && !IsBswapRHS)
101 return nullptr;
102
103 if (!IsBswapLHS && !ConstLHS)
104 return nullptr;
105
106 if (!IsBswapRHS && !ConstRHS)
107 return nullptr;
108
109 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
110 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
111 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
112 Builder->getInt(ConstLHS->getValue().byteSwap());
113
114 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
115 Builder->getInt(ConstRHS->getValue().byteSwap());
116
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000117 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000118 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000119 return Builder->CreateCall(F, BinOp);
120}
121
Sanjay Patel18549272015-09-08 18:24:36 +0000122/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000123/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
124Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000125 ConstantInt *OpRHS,
126 ConstantInt *AndRHS,
127 BinaryOperator &TheAnd) {
128 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000129 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000130 if (!Op->isShift())
131 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
132
133 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000134 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000135 case Instruction::Xor:
136 if (Op->hasOneUse()) {
137 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
138 Value *And = Builder->CreateAnd(X, AndRHS);
139 And->takeName(Op);
140 return BinaryOperator::CreateXor(And, Together);
141 }
142 break;
143 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000144 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000145 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
146 if (TogetherCI && !TogetherCI->isZero()){
147 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
148 // NOTE: This reduces the number of bits set in the & mask, which
149 // can expose opportunities for store narrowing.
150 Together = ConstantExpr::getXor(AndRHS, Together);
151 Value *And = Builder->CreateAnd(X, Together);
152 And->takeName(Op);
153 return BinaryOperator::CreateOr(And, OpRHS);
154 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000155 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000156
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157 break;
158 case Instruction::Add:
159 if (Op->hasOneUse()) {
160 // Adding a one to a single bit bit-field should be turned into an XOR
161 // of the bit. First thing to check is to see if this AND is with a
162 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000163 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000164
165 // If there is only one bit set.
166 if (AndRHSV.isPowerOf2()) {
167 // Ok, at this point, we know that we are masking the result of the
168 // ADD down to exactly one bit. If the constant we are adding has
169 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000170 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000171
172 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000173 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174 // If not, the only thing that can effect the output of the AND is
175 // the bit specified by AndRHSV. If that bit is set, the effect of
176 // the XOR is to toggle the bit. If it is clear, then the ADD has
177 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000178 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000179 TheAnd.setOperand(0, X);
180 return &TheAnd;
181 } else {
182 // Pull the XOR out of the AND.
183 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
184 NewAnd->takeName(Op);
185 return BinaryOperator::CreateXor(NewAnd, AndRHS);
186 }
187 }
188 }
189 }
190 break;
191
192 case Instruction::Shl: {
193 // We know that the AND will not produce any of the bits shifted in, so if
194 // the anded constant includes them, clear them now!
195 //
196 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
197 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
198 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000199 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000200
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000201 if (CI->getValue() == ShlMask)
202 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000203 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000204
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000205 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000206 TheAnd.setOperand(1, CI);
207 return &TheAnd;
208 }
209 break;
210 }
211 case Instruction::LShr: {
212 // We know that the AND will not produce any of the bits shifted in, so if
213 // the anded constant includes them, clear them now! This only applies to
214 // unsigned shifts, because a signed shr may bring in set bits!
215 //
216 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
217 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
218 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000219 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000220
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000221 if (CI->getValue() == ShrMask)
222 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000223 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000224
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000225 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000226 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
227 return &TheAnd;
228 }
229 break;
230 }
231 case Instruction::AShr:
232 // Signed shr.
233 // See if this is shifting in some sign extension, then masking it out
234 // with an and.
235 if (Op->hasOneUse()) {
236 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
237 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
238 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000239 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000240 if (C == AndRHS) { // Masking out bits shifted in.
241 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
242 // Make the argument unsigned.
243 Value *ShVal = Op->getOperand(0);
244 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
245 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
246 }
247 }
248 break;
249 }
Craig Topperf40110f2014-04-25 05:29:35 +0000250 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000251}
252
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000253/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000254/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
255/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000256Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000257 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000258 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000259 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000260
Sanjay Patel85d79742016-08-31 19:49:56 +0000261 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000262 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000263 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000264
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000265 // V >= Min && V < Hi --> V < Hi
266 // V < Min || V >= Hi --> V >= Hi
267 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000268 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000269 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000270 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000271 }
272
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000273 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
274 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000275 Value *VMinusLo =
276 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
277 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000278 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000279}
280
Sanjay Patel77bf6222017-04-03 16:53:12 +0000281/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
282/// that can be simplified.
283/// One of A and B is considered the mask. The other is the value. This is
284/// described as the "AMask" or "BMask" part of the enum. If the enum contains
285/// only "Mask", then both A and B can be considered masks. If A is the mask,
286/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
287/// If both A and C are constants, this proof is also easy.
288/// For the following explanations, we assume that A is the mask.
289///
290/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
291/// bits of A are set in B.
292/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
293///
294/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
295/// bits of A are cleared in B.
296/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
297///
298/// "Mixed" declares that (A & B) == C and C might or might not contain any
299/// number of one bits and zero bits.
300/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
301///
302/// "Not" means that in above descriptions "==" should be replaced by "!=".
303/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
304///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000305/// If the mask A contains a single bit, then the following is equivalent:
306/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
307/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
308enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000309 AMask_AllOnes = 1,
310 AMask_NotAllOnes = 2,
311 BMask_AllOnes = 4,
312 BMask_NotAllOnes = 8,
313 Mask_AllZeros = 16,
314 Mask_NotAllZeros = 32,
315 AMask_Mixed = 64,
316 AMask_NotMixed = 128,
317 BMask_Mixed = 256,
318 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000319};
320
Sanjay Patel77bf6222017-04-03 16:53:12 +0000321/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
322/// satisfies.
323static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
324 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000325 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
326 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
327 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000328 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
329 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
330 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
331 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000332 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000333 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000334 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
335 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
336 if (IsAPow2)
337 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
338 : (AMask_AllOnes | AMask_Mixed));
339 if (IsBPow2)
340 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
341 : (BMask_AllOnes | BMask_Mixed));
342 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000343 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000344
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000346 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
347 : (AMask_NotAllOnes | AMask_NotMixed));
348 if (IsAPow2)
349 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
350 : (Mask_AllZeros | AMask_Mixed));
351 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
352 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000353 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000354
Craig Topperae48cb22012-12-20 07:15:54 +0000355 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000356 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
357 : (BMask_NotAllOnes | BMask_NotMixed));
358 if (IsBPow2)
359 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
360 : (Mask_AllZeros | BMask_Mixed));
361 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
362 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000363 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000364
365 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000366}
367
Tim Northoverc0756c42013-09-04 11:57:13 +0000368/// Convert an analysis of a masked ICmp into its equivalent if all boolean
369/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
370/// is adjacent to the corresponding normal flag (recording ==), this just
371/// involves swapping those bits over.
372static unsigned conjugateICmpMask(unsigned Mask) {
373 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000374 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
375 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000376 << 1;
377
Sanjay Patel77bf6222017-04-03 16:53:12 +0000378 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
379 AMask_NotMixed | BMask_NotMixed))
380 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000381
382 return NewMask;
383}
384
Sanjay Patel77bf6222017-04-03 16:53:12 +0000385/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
386/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
387/// RHS satisfy.
388static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
389 Value *&D, Value *&E, ICmpInst *LHS,
390 ICmpInst *RHS,
391 ICmpInst::Predicate &PredL,
392 ICmpInst::Predicate &PredR) {
393 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
394 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000395 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000396 if (LHS->getOperand(0)->getType()->isVectorTy())
397 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000398
399 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000400 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000401 // and L11 & L12 == L21 & L22. The same goes for RHS.
402 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000403 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000404 // above.
405 Value *L1 = LHS->getOperand(0);
406 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000407 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000408 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000409 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000410 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000411 } else {
412 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000413 if (!L1->getType()->isIntegerTy()) {
414 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000415 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000416 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
417 // Any icmp can be viewed as being trivially masked; if it allows us to
418 // remove one, it's worth it.
419 L11 = L1;
420 L12 = Constant::getAllOnesValue(L1->getType());
421 }
422
423 if (!L2->getType()->isIntegerTy()) {
424 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000425 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000426 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
427 L21 = L2;
428 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000429 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000430 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000431
432 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000433 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000434 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000435
436 Value *R1 = RHS->getOperand(0);
437 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000438 Value *R11, *R12;
439 bool Ok = false;
440 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000441 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000442 A = R11;
443 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000444 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000445 A = R12;
446 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000447 } else {
448 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000449 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000450 E = R2;
451 R1 = nullptr;
452 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000453 } else if (R1->getType()->isIntegerTy()) {
454 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
455 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000456 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000457 R11 = R1;
458 R12 = Constant::getAllOnesValue(R1->getType());
459 }
460
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000461 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000462 A = R11;
463 D = R12;
464 E = R2;
465 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000466 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000467 A = R12;
468 D = R11;
469 E = R2;
470 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000471 }
472 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000473
474 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000475 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000476 return 0;
477
Chad Rosier58919cc2016-05-09 21:37:43 +0000478 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000479 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000480 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
481 R11 = R2;
482 R12 = Constant::getAllOnesValue(R2->getType());
483 }
484
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000485 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000486 A = R11;
487 D = R12;
488 E = R1;
489 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000490 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000491 A = R12;
492 D = R11;
493 E = R1;
494 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000495 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000496 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000497 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000498 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000499 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000500 return 0;
501
502 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000503 B = L12;
504 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000505 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000506 B = L11;
507 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000508 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000509 B = L22;
510 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000511 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000512 B = L21;
513 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000514 }
515
Sanjay Patel77bf6222017-04-03 16:53:12 +0000516 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
517 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000518 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000519}
Sanjay Patel18549272015-09-08 18:24:36 +0000520
521/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
522/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000523static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
524 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000525 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000526 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
527 unsigned Mask =
528 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
529 if (Mask == 0)
530 return nullptr;
531
532 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
533 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000534
Tim Northoverc0756c42013-09-04 11:57:13 +0000535 // In full generality:
536 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
537 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
538 //
539 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
540 // equivalent to (icmp (A & X) !Op Y).
541 //
542 // Therefore, we can pretend for the rest of this function that we're dealing
543 // with the conjunction, provided we flip the sense of any comparisons (both
544 // input and output).
545
546 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000547 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000548 if (!IsAnd) {
549 // Convert the masking analysis into its equivalent with negated
550 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000551 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000552 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000553
Sanjay Patel77bf6222017-04-03 16:53:12 +0000554 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000555 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000556 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000557 Value *NewOr = Builder->CreateOr(B, D);
558 Value *NewAnd = Builder->CreateAnd(A, NewOr);
559 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000560 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000561 // with B and D, having a single bit set.
562 Value *Zero = Constant::getNullValue(A->getType());
563 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000565 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000566 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000567 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000568 Value *NewOr = Builder->CreateOr(B, D);
569 Value *NewAnd = Builder->CreateAnd(A, NewOr);
570 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000571 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000572 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000573 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000574 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000575 Value *NewAnd1 = Builder->CreateAnd(B, D);
576 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
577 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000578 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000579
580 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000581 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000582 // easy cases for now" decision.
583 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000584 if (!BCst)
585 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000586 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000587 if (!DCst)
588 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000589
Sanjay Patel77bf6222017-04-03 16:53:12 +0000590 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000591 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
592 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
593 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
594 // Only valid if one of the masks is a superset of the other (check "B&D" is
595 // the same as either B or D).
596 APInt NewMask = BCst->getValue() & DCst->getValue();
597
598 if (NewMask == BCst->getValue())
599 return LHS;
600 else if (NewMask == DCst->getValue())
601 return RHS;
602 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000603
604 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000605 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
606 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
607 // Only valid if one of the masks is a superset of the other (check "B|D" is
608 // the same as either B or D).
609 APInt NewMask = BCst->getValue() | DCst->getValue();
610
611 if (NewMask == BCst->getValue())
612 return LHS;
613 else if (NewMask == DCst->getValue())
614 return RHS;
615 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000616
617 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000618 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000619 // We already know that B & C == C && D & E == E.
620 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
621 // C and E, which are shared by both the mask B and the mask D, don't
622 // contradict, then we can transform to
623 // -> (icmp eq (A & (B|D)), (C|E))
624 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000625 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000626 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000627 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000628 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000629 if (!CCst)
630 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000631 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000632 if (!ECst)
633 return nullptr;
634 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000635 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000636 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000637 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000638
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000639 // If there is a conflict, we should actually return a false for the
640 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000641 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000642 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000643 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000644
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000645 Value *NewOr1 = Builder->CreateOr(B, D);
646 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
647 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
648 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000649 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000650
Craig Topperf40110f2014-04-25 05:29:35 +0000651 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000652}
653
Erik Ecksteind1817522014-12-03 10:39:15 +0000654/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
655/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
656/// If \p Inverted is true then the check is for the inverted range, e.g.
657/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
658Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
659 bool Inverted) {
660 // Check the lower range comparison, e.g. x >= 0
661 // InstCombine already ensured that if there is a constant it's on the RHS.
662 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
663 if (!RangeStart)
664 return nullptr;
665
666 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
667 Cmp0->getPredicate());
668
669 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
670 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
671 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
672 return nullptr;
673
674 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
675 Cmp1->getPredicate());
676
677 Value *Input = Cmp0->getOperand(0);
678 Value *RangeEnd;
679 if (Cmp1->getOperand(0) == Input) {
680 // For the upper range compare we have: icmp x, n
681 RangeEnd = Cmp1->getOperand(1);
682 } else if (Cmp1->getOperand(1) == Input) {
683 // For the upper range compare we have: icmp n, x
684 RangeEnd = Cmp1->getOperand(0);
685 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
686 } else {
687 return nullptr;
688 }
689
690 // Check the upper range comparison, e.g. x < n
691 ICmpInst::Predicate NewPred;
692 switch (Pred1) {
693 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
694 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
695 default: return nullptr;
696 }
697
698 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000699 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
700 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000701 return nullptr;
702
703 if (Inverted)
704 NewPred = ICmpInst::getInversePredicate(NewPred);
705
706 return Builder->CreateICmp(NewPred, Input, RangeEnd);
707}
708
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000709static Value *
710foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
711 bool JoinedByAnd,
712 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000713 Value *X = LHS->getOperand(0);
714 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000715 return nullptr;
716
Sanjay Patelef9f5862017-04-15 17:55:06 +0000717 const APInt *C1, *C2;
718 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
719 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000720 return nullptr;
721
722 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
723 ICmpInst::Predicate Pred = LHS->getPredicate();
724 if (Pred != RHS->getPredicate())
725 return nullptr;
726 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
727 return nullptr;
728 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
729 return nullptr;
730
731 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000732 if (C1->ugt(*C2))
733 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000734
Sanjay Patelef9f5862017-04-15 17:55:06 +0000735 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000736 if (Xor.isPowerOf2()) {
737 // If LHSC and RHSC differ by only one bit, then set that bit in X and
738 // compare against the larger constant:
739 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
740 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
741 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
742 // 'and' because that may lead to smaller codegen from a smaller constant.
743 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000744 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000745 }
746
747 // Special case: get the ordering right when the values wrap around zero.
748 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000749 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000750 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000751
Sanjay Patelef9f5862017-04-15 17:55:06 +0000752 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000753 // (X == 13 || X == 14) --> X - 13 <=u 1
754 // (X != 13 && X != 14) --> X - 13 >u 1
755 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000756 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000757 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
758 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
759 }
760
761 return nullptr;
762}
763
Craig Topperda6ea0d2017-06-16 05:10:37 +0000764// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
765// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
766Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
767 bool JoinedByAnd,
768 Instruction &CxtI) {
769 ICmpInst::Predicate Pred = LHS->getPredicate();
770 if (Pred != RHS->getPredicate())
771 return nullptr;
772 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
773 return nullptr;
774 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
775 return nullptr;
776
777 // TODO support vector splats
778 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
779 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
780 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
781 return nullptr;
782
783 Value *A, *B, *C, *D;
784 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
785 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
786 if (A == D || B == D)
787 std::swap(C, D);
788 if (B == C)
789 std::swap(A, B);
790
791 if (A == C &&
792 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
793 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
794 Value *Mask = Builder->CreateOr(B, D);
795 Value *Masked = Builder->CreateAnd(A, Mask);
796 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
797 return Builder->CreateICmp(NewPred, Masked, Mask);
798 }
799 }
800
801 return nullptr;
802}
803
Sanjay Patel18549272015-09-08 18:24:36 +0000804/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000805Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
806 Instruction &CxtI) {
807 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
808 // if K1 and K2 are a one-bit mask.
809 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
810 return V;
811
Sanjay Patel519a87a2017-04-05 17:38:34 +0000812 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000813
814 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000815 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000816 if (LHS->getOperand(0) == RHS->getOperand(1) &&
817 LHS->getOperand(1) == RHS->getOperand(0))
818 LHS->swapOperands();
819 if (LHS->getOperand(0) == RHS->getOperand(0) &&
820 LHS->getOperand(1) == RHS->getOperand(1)) {
821 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
822 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
823 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000824 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000825 }
826 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000827
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000828 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000829 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000830 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000831
Erik Ecksteind1817522014-12-03 10:39:15 +0000832 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
833 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
834 return V;
835
836 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
837 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
838 return V;
839
Sanjay Patelef9f5862017-04-15 17:55:06 +0000840 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
841 return V;
842
Chris Lattner0a8191e2010-01-05 07:50:36 +0000843 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000844 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000845 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
846 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
847 if (!LHSC || !RHSC)
848 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000849
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000851 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000852 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000853 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000854 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
855 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000856 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000857 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000858 }
859 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000860
Benjamin Kramer101720f2011-04-28 20:09:57 +0000861 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000862 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000863 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000864 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
865 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000866 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000868
869 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000870 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000871 if (match(RHS0, m_Trunc(m_Value(V))) &&
872 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000873 SmallC = RHSC;
874 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000875 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
876 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000877 SmallC = LHSC;
878 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000879 }
880
Sanjay Patel519a87a2017-04-05 17:38:34 +0000881 if (SmallC && BigC) {
882 unsigned BigBitSize = BigC->getType()->getBitWidth();
883 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000884
885 // Check that the low bits are zero.
886 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000887 if ((Low & AndC->getValue()).isNullValue() &&
888 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000889 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
890 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
891 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
892 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000893 }
894 }
895 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000896
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 // From here on, we only handle:
898 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000899 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000900 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000901
Sanjay Patel519a87a2017-04-05 17:38:34 +0000902 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
903 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
904 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
905 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
906 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000907 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000908
Chris Lattner0a8191e2010-01-05 07:50:36 +0000909 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000910 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000911 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000912
Chris Lattner0a8191e2010-01-05 07:50:36 +0000913 // Ensure that the larger constant is on the RHS.
914 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000915 if (CmpInst::isSigned(PredL) ||
916 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000917 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000918 else
919 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000920
Chris Lattner0a8191e2010-01-05 07:50:36 +0000921 if (ShouldSwap) {
922 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000923 std::swap(LHSC, RHSC);
924 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 }
926
Dan Gohman4a618822010-02-10 16:03:48 +0000927 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000928 // comparing a value against two constants and and'ing the result
929 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000930 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
931 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000932 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000933 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934
Sanjay Patel519a87a2017-04-05 17:38:34 +0000935 switch (PredL) {
936 default:
937 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000938 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000939 switch (PredR) {
940 default:
941 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000942 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000943 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000944 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000945 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000946 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000947 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000948 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000950 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000951 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000952 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000953 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000954 // Potential folds for this case should already be handled.
955 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 }
957 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000959 switch (PredR) {
960 default:
961 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000962 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000963 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000964 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000965 break; // (X u> 13 & X != 15) -> no change
966 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000967 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
968 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000969 }
970 break;
971 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000972 switch (PredR) {
973 default:
974 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000975 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000976 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000977 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000978 break; // (X s> 13 & X != 15) -> no change
979 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000980 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000981 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000982 }
983 break;
984 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000985
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987}
988
Sanjay Patel18549272015-09-08 18:24:36 +0000989/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
990/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000991Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000992 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
993 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
994 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
995
996 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
997 // Swap RHS operands to match LHS.
998 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
999 std::swap(Op1LHS, Op1RHS);
1000 }
1001
1002 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1003 // Suppose the relation between x and y is R, where R is one of
1004 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1005 // testing the desired relations.
1006 //
1007 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1008 // bool(R & CC0) && bool(R & CC1)
1009 // = bool((R & CC0) & (R & CC1))
1010 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1011 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1012 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1013 Builder);
1014
Chris Lattner0a8191e2010-01-05 07:50:36 +00001015 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1016 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001017 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001018 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001019
Chris Lattner0a8191e2010-01-05 07:50:36 +00001020 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1021 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1022 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1023 // If either of the constants are nans, then the whole thing returns
1024 // false.
1025 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001026 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001027 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001029
Chris Lattner0a8191e2010-01-05 07:50:36 +00001030 // Handle vector zeros. This occurs because the canonical form of
1031 // "fcmp ord x,x" is "fcmp ord x, 0".
1032 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1033 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001034 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001035 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001036 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001037
Craig Topperf40110f2014-04-25 05:29:35 +00001038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001039}
1040
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001041/// Match De Morgan's Laws:
1042/// (~A & ~B) == (~(A | B))
1043/// (~A | ~B) == (~(A & B))
1044static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001045 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001046 auto Opcode = I.getOpcode();
1047 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1048 "Trying to match De Morgan's Laws with something other than and/or");
1049
Sanjay Patel7caaa792017-05-09 20:05:05 +00001050 // Flip the logic operation.
1051 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1052
1053 Value *A, *B;
1054 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1055 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1056 !IsFreeToInvert(A, A->hasOneUse()) &&
1057 !IsFreeToInvert(B, B->hasOneUse())) {
1058 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1059 return BinaryOperator::CreateNot(AndOr);
1060 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001061
1062 return nullptr;
1063}
1064
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001065bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1066 Value *CastSrc = CI->getOperand(0);
1067
1068 // Noop casts and casts of constants should be eliminated trivially.
1069 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1070 return false;
1071
1072 // If this cast is paired with another cast that can be eliminated, we prefer
1073 // to have it eliminated.
1074 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1075 if (isEliminableCastPair(PrecedingCI, CI))
1076 return false;
1077
1078 // If this is a vector sext from a compare, then we don't want to break the
1079 // idiom where each element of the extended vector is either zero or all ones.
1080 if (CI->getOpcode() == Instruction::SExt &&
1081 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1082 return false;
1083
1084 return true;
1085}
1086
Sanjay Patel60312bc42016-09-12 00:16:23 +00001087/// Fold {and,or,xor} (cast X), C.
1088static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1089 InstCombiner::BuilderTy *Builder) {
1090 Constant *C;
1091 if (!match(Logic.getOperand(1), m_Constant(C)))
1092 return nullptr;
1093
1094 auto LogicOpc = Logic.getOpcode();
1095 Type *DestTy = Logic.getType();
1096 Type *SrcTy = Cast->getSrcTy();
1097
Sanjay Pateld1e81192017-06-22 15:46:54 +00001098 // Move the logic operation ahead of a zext if the constant is unchanged in
1099 // the smaller source type. Performing the logic in a smaller type may provide
1100 // more information to later folds, and the smaller logic instruction may be
1101 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001102 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001103 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1104 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1105 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1106 if (ZextTruncC == C) {
1107 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1108 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1109 return new ZExtInst(NewOp, DestTy);
1110 }
1111 }
1112
1113 return nullptr;
1114}
1115
1116/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001117Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001118 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001119 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001120
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001122 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001123 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001124 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001125
Sanjay Patel9bba7502016-03-03 19:19:04 +00001126 // This must be a cast from an integer or integer vector source type to allow
1127 // transformation of the logic operation to the source type.
1128 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001129 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001130 if (!SrcTy->isIntOrIntVectorTy())
1131 return nullptr;
1132
Sanjay Patel60312bc42016-09-12 00:16:23 +00001133 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1134 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001135
Sanjay Patel9bba7502016-03-03 19:19:04 +00001136 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1137 if (!Cast1)
1138 return nullptr;
1139
1140 // Both operands of the logic operation are casts. The casts must be of the
1141 // same type for reduction.
1142 auto CastOpcode = Cast0->getOpcode();
1143 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001144 return nullptr;
1145
1146 Value *Cast0Src = Cast0->getOperand(0);
1147 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001148
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001149 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001150 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001151 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1152 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001153 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001154 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001155
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001156 // For now, only 'and'/'or' have optimizations after this.
1157 if (LogicOpc == Instruction::Xor)
1158 return nullptr;
1159
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001160 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001161 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001162 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1163 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1164 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001165 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001166 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001167 if (Res)
1168 return CastInst::Create(CastOpcode, Res, DestTy);
1169 return nullptr;
1170 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001171
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001172 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001173 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001174 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1175 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1176 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001177 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1178 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001179 if (Res)
1180 return CastInst::Create(CastOpcode, Res, DestTy);
1181 return nullptr;
1182 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001183
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001184 return nullptr;
1185}
1186
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001187static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1188 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1189
1190 // Canonicalize SExt or Not to the LHS
1191 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1192 std::swap(Op0, Op1);
1193 }
1194
1195 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1196 Value *X = nullptr;
1197 if (match(Op0, m_SExt(m_Value(X))) &&
1198 X->getType()->getScalarType()->isIntegerTy(1)) {
1199 Value *Zero = Constant::getNullValue(Op1->getType());
1200 return SelectInst::Create(X, Op1, Zero);
1201 }
1202
1203 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1204 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1205 X->getType()->getScalarType()->isIntegerTy(1)) {
1206 Value *Zero = Constant::getNullValue(Op0->getType());
1207 return SelectInst::Create(X, Zero, Op1);
1208 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001209
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001210 return nullptr;
1211}
1212
Sanjay Patele0c26e02017-04-23 22:00:02 +00001213static Instruction *foldAndToXor(BinaryOperator &I,
1214 InstCombiner::BuilderTy &Builder) {
1215 assert(I.getOpcode() == Instruction::And);
1216 Value *Op0 = I.getOperand(0);
1217 Value *Op1 = I.getOperand(1);
1218 Value *A, *B;
1219
1220 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1221 // (A | B) & ~(A & B) --> A ^ B
1222 // (A | B) & ~(B & A) --> A ^ B
1223 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1224 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1225 return BinaryOperator::CreateXor(A, B);
1226
1227 // (A | ~B) & (~A | B) --> ~(A ^ B)
1228 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1229 // (~B | A) & (~A | B) --> ~(A ^ B)
1230 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001231 if (Op0->hasOneUse() || Op1->hasOneUse())
1232 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1233 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1234 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001235
1236 return nullptr;
1237}
1238
1239static Instruction *foldOrToXor(BinaryOperator &I,
1240 InstCombiner::BuilderTy &Builder) {
1241 assert(I.getOpcode() == Instruction::Or);
1242 Value *Op0 = I.getOperand(0);
1243 Value *Op1 = I.getOperand(1);
1244 Value *A, *B;
1245
1246 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1247 // (A & B) | ~(A | B) --> ~(A ^ B)
1248 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001249 if (Op0->hasOneUse() || Op1->hasOneUse())
1250 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1251 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1252 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001253
1254 // (A & ~B) | (~A & B) --> A ^ B
1255 // (A & ~B) | (B & ~A) --> A ^ B
1256 // (~B & A) | (~A & B) --> A ^ B
1257 // (~B & A) | (B & ~A) --> A ^ B
1258 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1259 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1260 return BinaryOperator::CreateXor(A, B);
1261
1262 return nullptr;
1263}
1264
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001265// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1266// here. We should standardize that construct where it is needed or choose some
1267// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001268Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001269 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1271
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001272 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001273 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001274
Craig Toppera4205622017-06-09 03:21:29 +00001275 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001276 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001277
Craig Topper9d4171a2012-12-20 07:09:41 +00001278 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279 // purpose is to compute bits we don't care about.
1280 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001281 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001282
Sanjay Patele0c26e02017-04-23 22:00:02 +00001283 // Do this before using distributive laws to catch simple and/or/not patterns.
1284 if (Instruction *Xor = foldAndToXor(I, *Builder))
1285 return Xor;
1286
1287 // (A|B)&(A|C) -> A|(B&C) etc
1288 if (Value *V = SimplifyUsingDistributiveLaws(I))
1289 return replaceInstUsesWith(I, V);
1290
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001291 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001292 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001293
Chris Lattner0a8191e2010-01-05 07:50:36 +00001294 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1295 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001296
1297 // Optimize a variety of ((val OP C1) & C2) combinations...
1298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1299 Value *Op0LHS = Op0I->getOperand(0);
1300 Value *Op0RHS = Op0I->getOperand(1);
1301 switch (Op0I->getOpcode()) {
1302 default: break;
1303 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001304 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001305 // If the mask is only needed on one incoming arm, push it up.
1306 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001307
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001308 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001309 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 // Not masking anything out for the LHS, move to RHS.
1311 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1312 Op0RHS->getName()+".masked");
1313 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1314 }
1315 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001316 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001317 // Not masking anything out for the RHS, move to LHS.
1318 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1319 Op0LHS->getName()+".masked");
1320 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1321 }
1322
1323 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001324 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001325 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001326 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001327 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001328 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1329
Chris Lattner0a8191e2010-01-05 07:50:36 +00001330 break;
1331
1332 case Instruction::Shl:
1333 case Instruction::LShr:
1334 // (1 << x) & 1 --> zext(x == 0)
1335 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001336 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001337 Value *NewICmp =
1338 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1339 return new ZExtInst(NewICmp, I.getType());
1340 }
1341 break;
1342 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001343
David Majnemerde55c602017-01-17 18:08:06 +00001344 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1345 // of X and OP behaves well when given trunc(C1) and X.
1346 switch (Op0I->getOpcode()) {
1347 default:
1348 break;
1349 case Instruction::Xor:
1350 case Instruction::Or:
1351 case Instruction::Mul:
1352 case Instruction::Add:
1353 case Instruction::Sub:
1354 Value *X;
1355 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001356 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001357 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1358 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1359 Value *BinOp;
1360 if (isa<ZExtInst>(Op0LHS))
1361 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1362 else
1363 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1364 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1365 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1366 return new ZExtInst(And, I.getType());
1367 }
1368 }
1369 }
1370
Chris Lattner0a8191e2010-01-05 07:50:36 +00001371 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1372 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1373 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001374 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001375
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001376 // If this is an integer truncation, and if the source is an 'and' with
1377 // immediate, transform it. This frequently occurs for bitfield accesses.
1378 {
Craig Topperf40110f2014-04-25 05:29:35 +00001379 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001380 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1381 // Change: and (trunc (and X, YC) to T), C2
1382 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001383 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001384 // other simplifications.
1385 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1386 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1387 C3 = ConstantExpr::getAnd(C3, AndRHS);
1388 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001389 }
1390 }
Craig Topper86173602017-04-04 20:26:25 +00001391 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392
Craig Topper86173602017-04-04 20:26:25 +00001393 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001394 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1395 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001396
Sanjay Patel7caaa792017-05-09 20:05:05 +00001397 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001398 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001399
Chris Lattner0a8191e2010-01-05 07:50:36 +00001400 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001401 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001402 // A&(A^B) => A & ~B
1403 {
1404 Value *tmpOp0 = Op0;
1405 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001406 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001407 if (A == Op1 || B == Op1 ) {
1408 tmpOp1 = Op0;
1409 tmpOp0 = Op1;
1410 // Simplify below
1411 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001412 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001413
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001414 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001415 if (B == tmpOp0) {
1416 std::swap(A, B);
1417 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001418 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001419 // A is originally -1 (or a vector of -1 and undefs), then we enter
1420 // an endless loop. By checking that A is non-constant we ensure that
1421 // we will never get to the loop.
1422 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001423 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001424 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001425 }
1426
1427 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001428 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001429 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001430 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001431 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001432
1433 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1434 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1435 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001436 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001437 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1438
1439 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1440 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1441 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001442 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001443 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001444
1445 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001446 // (A | B) & (B ^ (~A)) -> (A & B)
1447 // (B | A) & ((~A) ^ B) -> (A & B)
1448 // (B | A) & (B ^ (~A)) -> (A & B)
1449 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1450 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001451 return BinaryOperator::CreateAnd(A, B);
1452
1453 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001454 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001455 // (B ^ (~A)) & (A | B) -> (A & B)
1456 // (B ^ (~A)) & (B | A) -> (A & B)
1457 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001458 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001459 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001460 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001461
David Majnemer5e96f1b2014-08-30 06:18:20 +00001462 {
1463 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1464 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1465 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001466 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001467 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001468
David Majnemer5e96f1b2014-08-30 06:18:20 +00001469 // TODO: Make this recursive; it's a little tricky because an arbitrary
1470 // number of 'and' instructions might have to be created.
1471 Value *X, *Y;
1472 if (LHS && match(Op1, 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(LHS, Cmp, 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(LHS, Cmp, 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 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1481 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001482 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001483 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001484 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001485 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001486 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001487 }
1488 }
1489
Chris Lattner4e8137d2010-02-11 06:26:33 +00001490 // If and'ing two fcmp, try combine them into one.
1491 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1492 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001493 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001494 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001495
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001496 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1497 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001498
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001499 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1500 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001501
Craig Topperf40110f2014-04-25 05:29:35 +00001502 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001503}
1504
Chad Rosiera00df492016-05-25 16:22:14 +00001505/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1506/// insert the new intrinsic and return it.
1507Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001508 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1509
1510 // Look through zero extends.
1511 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1512 Op0 = Ext->getOperand(0);
1513
1514 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1515 Op1 = Ext->getOperand(0);
1516
1517 // (A | B) | C and A | (B | C) -> bswap if possible.
1518 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1519 match(Op1, m_Or(m_Value(), m_Value()));
1520
1521 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1522 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1523 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1524
1525 // (A & B) | (C & D) -> bswap if possible.
1526 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1527 match(Op1, m_And(m_Value(), m_Value()));
1528
1529 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1530 return nullptr;
1531
James Molloyf01488e2016-01-15 09:20:19 +00001532 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001533 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001534 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001535 Instruction *LastInst = Insts.pop_back_val();
1536 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001537
James Molloyf01488e2016-01-15 09:20:19 +00001538 for (auto *Inst : Insts)
1539 Worklist.Add(Inst);
1540 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001541}
1542
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001543/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1544static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1545 unsigned NumElts = C1->getType()->getVectorNumElements();
1546 for (unsigned i = 0; i != NumElts; ++i) {
1547 Constant *EltC1 = C1->getAggregateElement(i);
1548 Constant *EltC2 = C2->getAggregateElement(i);
1549 if (!EltC1 || !EltC2)
1550 return false;
1551
1552 // One element must be all ones, and the other must be all zeros.
1553 // FIXME: Allow undef elements.
1554 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1555 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1556 return false;
1557 }
1558 return true;
1559}
1560
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001561/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1562/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1563/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001564static Value *getSelectCondition(Value *A, Value *B,
1565 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001566 // If these are scalars or vectors of i1, A can be used directly.
1567 Type *Ty = A->getType();
1568 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1569 return A;
1570
1571 // If A and B are sign-extended, look through the sexts to find the booleans.
1572 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001573 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001574 if (match(A, m_SExt(m_Value(Cond))) &&
1575 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001576 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1577 NotB = peekThroughBitcast(NotB, true);
1578 if (match(NotB, m_SExt(m_Specific(Cond))))
1579 return Cond;
1580 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001581
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001582 // All scalar (and most vector) possibilities should be handled now.
1583 // Try more matches that only apply to non-splat constant vectors.
1584 if (!Ty->isVectorTy())
1585 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001586
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001587 // If both operands are constants, see if the constants are inverse bitmasks.
1588 Constant *AC, *BC;
1589 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1590 areInverseVectorBitmasks(AC, BC))
1591 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1592
1593 // If both operands are xor'd with constants using the same sexted boolean
1594 // operand, see if the constants are inverse bitmasks.
1595 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1596 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1597 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1598 areInverseVectorBitmasks(AC, BC)) {
1599 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1600 return Builder.CreateXor(Cond, AC);
1601 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001602 return nullptr;
1603}
1604
1605/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1606/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001607static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001608 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001609 // The potential condition of the select may be bitcasted. In that case, look
1610 // through its bitcast and the corresponding bitcast of the 'not' condition.
1611 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001612 A = peekThroughBitcast(A, true);
1613 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001614
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001615 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001616 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001617 // The bitcasts will either all exist or all not exist. The builder will
1618 // not create unnecessary casts if the types already match.
1619 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1620 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1621 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1622 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001623 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001624
Craig Topperf40110f2014-04-25 05:29:35 +00001625 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001626}
1627
Sanjay Patel18549272015-09-08 18:24:36 +00001628/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001629Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001630 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001631 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1632 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001633 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1634 return V;
1635
1636 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1637
Sanjay Patel519a87a2017-04-05 17:38:34 +00001638 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1639 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001640
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001641 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1642 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1643 // The original condition actually refers to the following two ranges:
1644 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1645 // We can fold these two ranges if:
1646 // 1) C1 and C2 is unsigned greater than C3.
1647 // 2) The two ranges are separated.
1648 // 3) C1 ^ C2 is one-bit mask.
1649 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1650 // This implies all values in the two ranges differ by exactly one bit.
1651
Sanjay Patel519a87a2017-04-05 17:38:34 +00001652 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1653 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1654 LHSC->getType() == RHSC->getType() &&
1655 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001656
1657 Value *LAdd = LHS->getOperand(0);
1658 Value *RAdd = RHS->getOperand(0);
1659
1660 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001661 ConstantInt *LAddC, *RAddC;
1662 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1663 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1664 LAddC->getValue().ugt(LHSC->getValue()) &&
1665 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001666
Sanjay Patel519a87a2017-04-05 17:38:34 +00001667 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1668 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1669 ConstantInt *MaxAddC = nullptr;
1670 if (LAddC->getValue().ult(RAddC->getValue()))
1671 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001672 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001673 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001674
Sanjay Patel519a87a2017-04-05 17:38:34 +00001675 APInt RRangeLow = -RAddC->getValue();
1676 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1677 APInt LRangeLow = -LAddC->getValue();
1678 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001679 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1680 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1681 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1682 : RRangeLow - LRangeLow;
1683
1684 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001685 RangeDiff.ugt(LHSC->getValue())) {
1686 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001687
Sanjay Patel519a87a2017-04-05 17:38:34 +00001688 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1689 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1690 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001691 }
1692 }
1693 }
1694 }
1695
Chris Lattner0a8191e2010-01-05 07:50:36 +00001696 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001697 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001698 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1699 LHS->getOperand(1) == RHS->getOperand(0))
1700 LHS->swapOperands();
1701 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1702 LHS->getOperand(1) == RHS->getOperand(1)) {
1703 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1704 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1705 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001706 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001707 }
1708 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001709
1710 // handle (roughly):
1711 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001712 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001713 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001714
Sanjay Patele4159d22017-04-10 19:38:36 +00001715 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001716 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1717 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1718 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001719 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001720 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001721 B = LHS0;
1722 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1723 A = RHS0;
1724 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001725 A = RHS->getOperand(1);
1726 }
1727 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1728 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001729 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001730 B = RHS0;
1731 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1732 A = LHS0;
1733 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001734 A = LHS->getOperand(1);
1735 }
1736 if (A && B)
1737 return Builder->CreateICmp(
1738 ICmpInst::ICMP_UGE,
1739 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1740 }
1741
Erik Ecksteind1817522014-12-03 10:39:15 +00001742 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1743 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1744 return V;
1745
1746 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1747 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1748 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001749
Sanjay Patelef9f5862017-04-15 17:55:06 +00001750 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1751 return V;
1752
David Majnemerc2a990b2013-07-05 00:31:17 +00001753 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001754 if (!LHSC || !RHSC)
1755 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001756
Sanjay Patel519a87a2017-04-05 17:38:34 +00001757 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001758 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001759 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001760 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001761 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001762 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001763 }
1764
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001765 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001766 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001767 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1768 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001769 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001770 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001771 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001772 }
1773
Chris Lattner0a8191e2010-01-05 07:50:36 +00001774 // From here on, we only handle:
1775 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001776 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001777 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001778
Sanjay Patel519a87a2017-04-05 17:38:34 +00001779 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1780 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1781 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1782 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1783 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001784 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001785
Chris Lattner0a8191e2010-01-05 07:50:36 +00001786 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001787 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001788 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001789
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 // Ensure that the larger constant is on the RHS.
1791 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001792 if (CmpInst::isSigned(PredL) ||
1793 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001794 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001795 else
1796 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001797
Chris Lattner0a8191e2010-01-05 07:50:36 +00001798 if (ShouldSwap) {
1799 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001800 std::swap(LHSC, RHSC);
1801 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001802 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001803
Dan Gohman4a618822010-02-10 16:03:48 +00001804 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805 // comparing a value against two constants and or'ing the result
1806 // together. Because of the above check, we know that we only have
1807 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1808 // icmp folding check above), that the two constants are not
1809 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001810 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811
Sanjay Patel519a87a2017-04-05 17:38:34 +00001812 switch (PredL) {
1813 default:
1814 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001815 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001816 switch (PredR) {
1817 default:
1818 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001820 // Potential folds for this case should already be handled.
1821 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001822 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1823 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001824 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001825 }
1826 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001828 switch (PredR) {
1829 default:
1830 llvm_unreachable("Unknown integer condition code!");
1831 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001832 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001833 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001834 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001835 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1836 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001837 }
1838 break;
1839 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001840 switch (PredR) {
1841 default:
1842 llvm_unreachable("Unknown integer condition code!");
1843 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001844 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001845 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001846 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001847 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001848 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001849 }
1850 break;
1851 }
Craig Topperf40110f2014-04-25 05:29:35 +00001852 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001853}
1854
Sanjay Patel18549272015-09-08 18:24:36 +00001855/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1856/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001857Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001858 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1859 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1860 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1861
1862 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1863 // Swap RHS operands to match LHS.
1864 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1865 std::swap(Op1LHS, Op1RHS);
1866 }
1867
1868 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1869 // This is a similar transformation to the one in FoldAndOfFCmps.
1870 //
1871 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1872 // bool(R & CC0) || bool(R & CC1)
1873 // = bool((R & CC0) | (R & CC1))
1874 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1875 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1876 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1877 Builder);
1878
Chris Lattner0a8191e2010-01-05 07:50:36 +00001879 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001880 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1882 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1883 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1884 // If either of the constants are nans, then the whole thing returns
1885 // true.
1886 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001887 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001888
Chris Lattner0a8191e2010-01-05 07:50:36 +00001889 // Otherwise, no need to compare the two constants, compare the
1890 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001891 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001892 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001893
Chris Lattner0a8191e2010-01-05 07:50:36 +00001894 // Handle vector zeros. This occurs because the canonical form of
1895 // "fcmp uno x,x" is "fcmp uno x, 0".
1896 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1897 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001898 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001899
Craig Topperf40110f2014-04-25 05:29:35 +00001900 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001901 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001902
Craig Topperf40110f2014-04-25 05:29:35 +00001903 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001904}
1905
Sanjay Patel18549272015-09-08 18:24:36 +00001906/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001907///
1908/// ((A | B) & C1) | (B & C2)
1909///
1910/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001911///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001912/// (A & C1) | B
1913///
1914/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001915static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1916 Value *A, Value *B, Value *C,
1917 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001918 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001919 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001920
Craig Topperf40110f2014-04-25 05:29:35 +00001921 Value *V1 = nullptr;
1922 ConstantInt *CI2 = nullptr;
1923 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001924
1925 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001926 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001927
1928 if (V1 == A || V1 == B) {
1929 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1930 return BinaryOperator::CreateOr(NewOp, V1);
1931 }
1932
Craig Topperf40110f2014-04-25 05:29:35 +00001933 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001934}
1935
David Majnemer5d1aeba2014-08-21 05:14:48 +00001936/// \brief This helper function folds:
1937///
Craig Toppera074c102017-06-21 18:57:00 +00001938/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001939///
1940/// into:
1941///
1942/// (A & C1) ^ B
1943///
1944/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001945static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1946 Value *A, Value *B, Value *C,
1947 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001948 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1949 if (!CI1)
1950 return nullptr;
1951
1952 Value *V1 = nullptr;
1953 ConstantInt *CI2 = nullptr;
1954 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1955 return nullptr;
1956
1957 APInt Xor = CI1->getValue() ^ CI2->getValue();
1958 if (!Xor.isAllOnesValue())
1959 return nullptr;
1960
1961 if (V1 == A || V1 == B) {
1962 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1963 return BinaryOperator::CreateXor(NewOp, V1);
1964 }
1965
1966 return nullptr;
1967}
1968
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001969// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1970// here. We should standardize that construct where it is needed or choose some
1971// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001972Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001973 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1975
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001976 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001977 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001978
Craig Toppera4205622017-06-09 03:21:29 +00001979 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001980 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001981
Craig Topper9d4171a2012-12-20 07:09:41 +00001982 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001983 // purpose is to compute bits we don't care about.
1984 if (SimplifyDemandedInstructionBits(I))
1985 return &I;
1986
Sanjay Patele0c26e02017-04-23 22:00:02 +00001987 // Do this before using distributive laws to catch simple and/or/not patterns.
1988 if (Instruction *Xor = foldOrToXor(I, *Builder))
1989 return Xor;
1990
1991 // (A&B)|(A&C) -> A&(B|C) etc
1992 if (Value *V = SimplifyUsingDistributiveLaws(I))
1993 return replaceInstUsesWith(I, V);
1994
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001995 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001996 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001997
Craig Topper86173602017-04-04 20:26:25 +00001998 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001999 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2000 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002001
Chad Rosiere5819e22016-05-26 14:58:51 +00002002 // Given an OR instruction, check to see if this is a bswap.
2003 if (Instruction *BSwap = MatchBSwap(I))
2004 return BSwap;
2005
Craig Topperafa07c52017-04-09 06:12:41 +00002006 {
2007 Value *A;
2008 const APInt *C;
2009 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2010 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2011 MaskedValueIsZero(Op1, *C, 0, &I)) {
2012 Value *NOr = Builder->CreateOr(A, Op1);
2013 NOr->takeName(Op0);
2014 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002015 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002016 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002017
Craig Topperafa07c52017-04-09 06:12:41 +00002018 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2019 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2020 MaskedValueIsZero(Op0, *C, 0, &I)) {
2021 Value *NOr = Builder->CreateOr(A, Op0);
2022 NOr->takeName(Op0);
2023 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002024 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002025 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002026 }
2027
Craig Topperafa07c52017-04-09 06:12:41 +00002028 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002029
Suyog Sardad64faf62014-07-22 18:09:41 +00002030 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002031 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2032 return BinaryOperator::CreateOr(A, Op1);
2033 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2034 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002035
2036 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002037 // The NOT is guaranteed to be in the RHS by complexity ordering.
2038 if (match(Op1, m_Not(m_Value(A))) &&
2039 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2040 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002041
Chris Lattner0a8191e2010-01-05 07:50:36 +00002042 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002043 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002044 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2045 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002046 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002047 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2048 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002049 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002050 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002051 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002052 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002053 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002054 ((V1 == B &&
2055 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2056 (V2 == B &&
2057 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002058 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002059 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002060 // Or commutes, try both ways.
2061 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002062 ((V1 == A &&
2063 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2064 (V2 == A &&
2065 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002066 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002067 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002068
Chris Lattner95188692010-01-11 06:55:24 +00002069 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002070 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002071 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002072 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002073 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002074 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002075 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002076 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2077 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002078 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002079 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002080 }
2081 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002082
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002083 // Don't try to form a select if it's unlikely that we'll get rid of at
2084 // least one of the operands. A select is generally more expensive than the
2085 // 'or' that it is replacing.
2086 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2087 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2088 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2089 return replaceInstUsesWith(I, V);
2090 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2097 return replaceInstUsesWith(I, V);
2098 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2099 return replaceInstUsesWith(I, V);
2100 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2101 return replaceInstUsesWith(I, V);
2102 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2103 return replaceInstUsesWith(I, V);
2104 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002105
Benjamin Kramer11743242010-07-12 13:34:22 +00002106 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002107 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2108 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2109 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002110 }
2111 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002112 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2113 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2114 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002115 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002116 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002117 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2118 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2119 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002120 }
2121 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002122 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2123 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2124 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002125 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002126 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002127
David Majnemer42af3602014-07-30 21:26:37 +00002128 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2129 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2130 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002131 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002132
2133 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2134 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2135 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002136 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002137
David Majnemerf1eda232014-08-14 06:41:38 +00002138 // ((B | C) & A) | B -> B | (A & C)
2139 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2140 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2141
Sanjay Patel7caaa792017-05-09 20:05:05 +00002142 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002143 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002144
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002145 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002146 bool SwappedForXor = false;
2147 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002148 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002149 SwappedForXor = true;
2150 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002151
2152 // A | ( A ^ B) -> A | B
2153 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002154 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002155 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2156 if (Op0 == A || Op0 == B)
2157 return BinaryOperator::CreateOr(A, B);
2158
Chad Rosier7813dce2012-04-26 23:29:14 +00002159 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2160 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2161 return BinaryOperator::CreateOr(A, B);
2162
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002163 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2164 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2165 return BinaryOperator::CreateOr(Not, Op0);
2166 }
2167 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2168 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2169 return BinaryOperator::CreateOr(Not, Op0);
2170 }
2171 }
2172
2173 // A | ~(A | B) -> A | ~B
2174 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002175 if (match(Op1, m_Not(m_Value(A))))
2176 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002177 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2178 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2179 B->getOpcode() == Instruction::Xor)) {
2180 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2181 B->getOperand(0);
2182 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2183 return BinaryOperator::CreateOr(Not, Op0);
2184 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002185
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002186 // (A & B) | (~A ^ B) -> (~A ^ B)
2187 // (A & B) | (B ^ ~A) -> (~A ^ B)
2188 // (B & A) | (~A ^ B) -> (~A ^ B)
2189 // (B & A) | (B ^ ~A) -> (~A ^ B)
2190 // The match order is important: match the xor first because the 'not'
2191 // operation defines 'A'. We do not need to match the xor as Op0 because the
2192 // xor was canonicalized to Op1 above.
2193 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2194 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002195 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2196
Eli Friedmane06535b2012-03-16 00:52:42 +00002197 if (SwappedForXor)
2198 std::swap(Op0, Op1);
2199
David Majnemer3d6f80b2014-11-28 19:58:29 +00002200 {
2201 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2202 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2203 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002204 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002205 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002206
David Majnemer3d6f80b2014-11-28 19:58:29 +00002207 // TODO: Make this recursive; it's a little tricky because an arbitrary
2208 // number of 'or' instructions might have to be created.
2209 Value *X, *Y;
2210 if (LHS && match(Op1, 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(LHS, Cmp, 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(LHS, Cmp, 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 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2219 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002220 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002221 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002222 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002223 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002224 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002225 }
2226 }
2227
Chris Lattner4e8137d2010-02-11 06:26:33 +00002228 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2229 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2230 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002231 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002232 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002233
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002234 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2235 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002236
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002237 // 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 +00002238 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002239 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002240 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002241 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002242 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002243 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2244
Owen Andersonc237a842010-09-13 17:59:27 +00002245 // Note: If we've gotten to the point of visiting the outer OR, then the
2246 // inner one couldn't be simplified. If it was a constant, then it won't
2247 // be simplified by a later pass either, so we try swapping the inner/outer
2248 // ORs in the hopes that we'll be able to simplify it this way.
2249 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002250 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002251 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2252 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2253 Value *Inner = Builder->CreateOr(A, Op1);
2254 Inner->takeName(Op0);
2255 return BinaryOperator::CreateOr(Inner, C1);
2256 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002257
Bill Wendling23242092013-02-16 23:41:36 +00002258 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2259 // Since this OR statement hasn't been optimized further yet, we hope
2260 // that this transformation will allow the new ORs to be optimized.
2261 {
Craig Topperf40110f2014-04-25 05:29:35 +00002262 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002263 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2264 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2265 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2266 Value *orTrue = Builder->CreateOr(A, C);
2267 Value *orFalse = Builder->CreateOr(B, D);
2268 return SelectInst::Create(X, orTrue, orFalse);
2269 }
2270 }
2271
Craig Topperf40110f2014-04-25 05:29:35 +00002272 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002273}
2274
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002275/// A ^ B can be specified using other logic ops in a variety of patterns. We
2276/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002277static Instruction *foldXorToXor(BinaryOperator &I,
2278 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002279 assert(I.getOpcode() == Instruction::Xor);
2280 Value *Op0 = I.getOperand(0);
2281 Value *Op1 = I.getOperand(1);
2282 Value *A, *B;
2283
2284 // There are 4 commuted variants for each of the basic patterns.
2285
2286 // (A & B) ^ (A | B) -> A ^ B
2287 // (A & B) ^ (B | A) -> A ^ B
2288 // (A | B) ^ (A & B) -> A ^ B
2289 // (A | B) ^ (B & A) -> A ^ B
2290 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2291 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2292 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2293 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2294 I.setOperand(0, A);
2295 I.setOperand(1, B);
2296 return &I;
2297 }
2298
2299 // (A | ~B) ^ (~A | B) -> A ^ B
2300 // (~B | A) ^ (~A | B) -> A ^ B
2301 // (~A | B) ^ (A | ~B) -> A ^ B
2302 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002303 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2304 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2305 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2306 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002307 I.setOperand(0, A);
2308 I.setOperand(1, B);
2309 return &I;
2310 }
2311
2312 // (A & ~B) ^ (~A & B) -> A ^ B
2313 // (~B & A) ^ (~A & B) -> A ^ B
2314 // (~A & B) ^ (A & ~B) -> A ^ B
2315 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002316 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2317 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2318 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2319 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002320 I.setOperand(0, A);
2321 I.setOperand(1, B);
2322 return &I;
2323 }
2324
Craig Topperf60ab472017-07-02 01:15:51 +00002325 // For the remaining cases we need to get rid of one of the operands.
2326 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2327 return nullptr;
2328
2329 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2330 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2331 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2332 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2333 // Complexity sorting ensures the not will be on the right side.
2334 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2335 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2336 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2337 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2338 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2339
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002340 return nullptr;
2341}
2342
Sanjay Patel5e456b92017-05-18 20:53:16 +00002343Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2344 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2345 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2346 LHS->getOperand(1) == RHS->getOperand(0))
2347 LHS->swapOperands();
2348 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2349 LHS->getOperand(1) == RHS->getOperand(1)) {
2350 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2351 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2352 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2353 bool isSigned = LHS->isSigned() || RHS->isSigned();
2354 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2355 }
2356 }
2357
Sanjay Pateladca8252017-06-20 12:40:55 +00002358 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2359 // into those logic ops. That is, try to turn this into an and-of-icmps
2360 // because we have many folds for that pattern.
2361 //
2362 // This is based on a truth table definition of xor:
2363 // X ^ Y --> (X | Y) & !(X & Y)
2364 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2365 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2366 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2367 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2368 // TODO: Independently handle cases where the 'and' side is a constant.
2369 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2370 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2371 RHS->setPredicate(RHS->getInversePredicate());
2372 return Builder->CreateAnd(LHS, RHS);
2373 }
2374 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002375 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002376 LHS->setPredicate(LHS->getInversePredicate());
2377 return Builder->CreateAnd(LHS, RHS);
2378 }
2379 }
2380 }
2381
Sanjay Patel5e456b92017-05-18 20:53:16 +00002382 return nullptr;
2383}
2384
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002385// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2386// here. We should standardize that construct where it is needed or choose some
2387// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002388Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002389 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2391
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002392 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002393 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002394
Craig Toppera4205622017-06-09 03:21:29 +00002395 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002396 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002397
Craig Topperf60ab472017-07-02 01:15:51 +00002398 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002399 return NewXor;
2400
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002401 // (A&B)^(A&C) -> A&(B^C) etc
2402 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002403 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002404
Craig Topper9d4171a2012-12-20 07:09:41 +00002405 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002406 // purpose is to compute bits we don't care about.
2407 if (SimplifyDemandedInstructionBits(I))
2408 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002409
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002410 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002411 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002412
Sanjay Patel6381db12017-05-02 15:31:40 +00002413 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2414 Value *X, *Y;
2415
2416 // We must eliminate the and/or (one-use) for these transforms to not increase
2417 // the instruction count.
2418 // ~(~X & Y) --> (X | ~Y)
2419 // ~(Y & ~X) --> (X | ~Y)
2420 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2421 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2422 return BinaryOperator::CreateOr(X, NotY);
2423 }
2424 // ~(~X | Y) --> (X & ~Y)
2425 // ~(Y | ~X) --> (X & ~Y)
2426 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2427 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2428 return BinaryOperator::CreateAnd(X, NotY);
2429 }
2430
Sanjay Patel3b863f82017-04-22 18:05:35 +00002431 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002432 BinaryOperator *NotVal;
2433 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2434 if (NotVal->getOpcode() == Instruction::And ||
2435 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002436 // Apply DeMorgan's Law when inverts are free:
2437 // ~(X & Y) --> (~X | ~Y)
2438 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002439 if (IsFreeToInvert(NotVal->getOperand(0),
2440 NotVal->getOperand(0)->hasOneUse()) &&
2441 IsFreeToInvert(NotVal->getOperand(1),
2442 NotVal->getOperand(1)->hasOneUse())) {
2443 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2444 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2445 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002446 return BinaryOperator::CreateOr(NotX, NotY);
2447 return BinaryOperator::CreateAnd(NotX, NotY);
2448 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002449 }
2450
2451 // ~(~X >>s Y) --> (X >>s Y)
2452 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2453 return BinaryOperator::CreateAShr(X, Y);
2454
2455 // If we are inverting a right-shifted constant, we may be able to eliminate
2456 // the 'not' by inverting the constant and using the opposite shift type.
2457 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2458 // but we must check that in case that transform has not fired yet.
2459 const APInt *C;
2460 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2461 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2462 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2463 return BinaryOperator::CreateLShr(NotC, Y);
2464 }
2465
2466 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2467 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2468 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2469 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002470 }
2471 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002472
Craig Topper798a19a2017-06-29 00:07:08 +00002473 // not (cmp A, B) = !cmp A, B
Sanjay Patel33439f92017-04-12 15:11:33 +00002474 ICmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002475 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002476 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2477 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002478 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002479
Craig Topper9d1821b2017-04-09 06:12:31 +00002480 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002481 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2482 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2483 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2484 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2485 Instruction::CastOps Opcode = Op0C->getOpcode();
2486 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002487 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002488 Op0C->getDestTy()))) {
2489 CI->setPredicate(CI->getInversePredicate());
2490 return CastInst::Create(Opcode, CI, Op0C->getType());
2491 }
2492 }
2493 }
2494 }
2495
2496 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2497 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002498 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002499 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2500 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002501 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2502 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002504
Chris Lattner0a8191e2010-01-05 07:50:36 +00002505 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2506 if (Op0I->getOpcode() == Instruction::Add) {
2507 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002508 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002510 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2511 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002512 } else if (RHSC->getValue().isSignMask()) {
2513 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002514 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2516
2517 }
2518 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002519 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002520 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2521 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002522 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002523 // Anything in both C1 and C2 is known to be zero, remove it from
2524 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002525 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002526 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002527 ConstantExpr::getNot(CommonBits));
2528 Worklist.Add(Op0I);
2529 I.setOperand(0, Op0I->getOperand(0));
2530 I.setOperand(1, NewRHS);
2531 return &I;
2532 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002533 } else if (Op0I->getOpcode() == Instruction::LShr) {
2534 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2535 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002536 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002537 ConstantInt *C1;
2538 if (Op0I->hasOneUse() &&
2539 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2540 E1->getOpcode() == Instruction::Xor &&
2541 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2542 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002543 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002544 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2545 FoldConst ^= C3->getValue();
2546 // Prepare the two operands.
2547 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2548 Opnd0->takeName(Op0I);
2549 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2550 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2551
2552 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2553 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554 }
2555 }
2556 }
Craig Topper86173602017-04-04 20:26:25 +00002557 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002558
Craig Topper86173602017-04-04 20:26:25 +00002559 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002560 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2561 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002562
Craig Topper76394602017-04-10 06:53:23 +00002563 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002564 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002565 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002566 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002567 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002568 std::swap(A, B);
2569 }
2570 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002571 I.swapOperands(); // Simplified below.
2572 std::swap(Op0, Op1);
2573 }
Craig Topper76394602017-04-10 06:53:23 +00002574 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002575 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002576 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002577 std::swap(A, B);
2578 }
2579 if (B == Op0) { // A^(B&A) -> (B&A)^A
2580 I.swapOperands(); // Simplified below.
2581 std::swap(Op0, Op1);
2582 }
2583 }
2584 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002585
Craig Topper76394602017-04-10 06:53:23 +00002586 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002588 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002589 if (A == Op1) // (B|A)^B == (A|B)^B
2590 std::swap(A, B);
2591 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002592 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002593 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002594 if (A == Op1) // (A&B)^A -> (B&A)^A
2595 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002596 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002597 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002598 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002599 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002600 }
2601 }
2602 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002603
Craig Topper76394602017-04-10 06:53:23 +00002604 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002605 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002606 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002607 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2608 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002609 if (D == A)
2610 return BinaryOperator::CreateXor(
2611 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2612 if (D == B)
2613 return BinaryOperator::CreateXor(
2614 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002615 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002616 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002617 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2618 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002619 if (D == A)
2620 return BinaryOperator::CreateXor(
2621 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2622 if (D == B)
2623 return BinaryOperator::CreateXor(
2624 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002625 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002626 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002627 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002628 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002629 return BinaryOperator::CreateOr(A, B);
2630 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002631 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002632 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002633 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002634 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002635
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002636 // (A & ~B) ^ ~A -> ~(A & B)
2637 // (~B & A) ^ ~A -> ~(A & B)
2638 Value *A, *B;
2639 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002640 match(Op1, m_Not(m_Specific(A))))
2641 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2642
Sanjay Patel5e456b92017-05-18 20:53:16 +00002643 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2644 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2645 if (Value *V = foldXorOfICmps(LHS, RHS))
2646 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002647
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002648 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2649 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002650
Craig Topperf40110f2014-04-25 05:29:35 +00002651 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002652}