blob: 9a6199fdafba7479eb076aef5fbc24a3010a5022 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
57 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
61 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Chris Lattner067459c2010-03-05 08:46:26 +000067 InstCombiner::BuilderTy *Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner067459c2010-03-05 08:46:26 +000075 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
79/// \param I Binary operator to transform.
80/// \return Pointer to node that must replace the original binary operator, or
81/// null pointer if no transformation was made.
82Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
Craig Topperc6948c22017-07-03 05:54:11 +000083 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
84
Craig Topper1e4643a2017-07-03 05:54:13 +000085 // TODO handle constant on one side with vectors.
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000086 Value *OldLHS = I.getOperand(0);
87 Value *OldRHS = I.getOperand(1);
88 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
89 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
90 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
91 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
92 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
93 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
94
95 if (!IsBswapLHS && !IsBswapRHS)
96 return nullptr;
97
98 if (!IsBswapLHS && !ConstLHS)
99 return nullptr;
100
101 if (!IsBswapRHS && !ConstRHS)
102 return nullptr;
103
104 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
105 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
106 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
107 Builder->getInt(ConstLHS->getValue().byteSwap());
108
109 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
110 Builder->getInt(ConstRHS->getValue().byteSwap());
111
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000112 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000113 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
114 I.getType());
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000115 return Builder->CreateCall(F, BinOp);
116}
117
Sanjay Patel18549272015-09-08 18:24:36 +0000118/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000119/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
120Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000121 ConstantInt *OpRHS,
122 ConstantInt *AndRHS,
123 BinaryOperator &TheAnd) {
124 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000125 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000126 if (!Op->isShift())
127 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
128
129 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000130 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000131 case Instruction::Xor:
132 if (Op->hasOneUse()) {
133 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
134 Value *And = Builder->CreateAnd(X, AndRHS);
135 And->takeName(Op);
136 return BinaryOperator::CreateXor(And, Together);
137 }
138 break;
139 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000140 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000141 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
142 if (TogetherCI && !TogetherCI->isZero()){
143 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
144 // NOTE: This reduces the number of bits set in the & mask, which
145 // can expose opportunities for store narrowing.
146 Together = ConstantExpr::getXor(AndRHS, Together);
147 Value *And = Builder->CreateAnd(X, Together);
148 And->takeName(Op);
149 return BinaryOperator::CreateOr(And, OpRHS);
150 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000151 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000152
Chris Lattner0a8191e2010-01-05 07:50:36 +0000153 break;
154 case Instruction::Add:
155 if (Op->hasOneUse()) {
156 // Adding a one to a single bit bit-field should be turned into an XOR
157 // of the bit. First thing to check is to see if this AND is with a
158 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000159 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000160
161 // If there is only one bit set.
162 if (AndRHSV.isPowerOf2()) {
163 // Ok, at this point, we know that we are masking the result of the
164 // ADD down to exactly one bit. If the constant we are adding has
165 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000166 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000167
168 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000169 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000170 // If not, the only thing that can effect the output of the AND is
171 // the bit specified by AndRHSV. If that bit is set, the effect of
172 // the XOR is to toggle the bit. If it is clear, then the ADD has
173 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000174 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000175 TheAnd.setOperand(0, X);
176 return &TheAnd;
177 } else {
178 // Pull the XOR out of the AND.
179 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
180 NewAnd->takeName(Op);
181 return BinaryOperator::CreateXor(NewAnd, AndRHS);
182 }
183 }
184 }
185 }
186 break;
187
188 case Instruction::Shl: {
189 // We know that the AND will not produce any of the bits shifted in, so if
190 // the anded constant includes them, clear them now!
191 //
192 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
193 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
194 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000195 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000196
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000197 if (CI->getValue() == ShlMask)
198 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000199 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000200
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000201 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000202 TheAnd.setOperand(1, CI);
203 return &TheAnd;
204 }
205 break;
206 }
207 case Instruction::LShr: {
208 // We know that the AND will not produce any of the bits shifted in, so if
209 // the anded constant includes them, clear them now! This only applies to
210 // unsigned shifts, because a signed shr may bring in set bits!
211 //
212 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
213 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
214 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000215 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000216
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000217 if (CI->getValue() == ShrMask)
218 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000219 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000220
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000221 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000222 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
223 return &TheAnd;
224 }
225 break;
226 }
227 case Instruction::AShr:
228 // Signed shr.
229 // See if this is shifting in some sign extension, then masking it out
230 // with an and.
231 if (Op->hasOneUse()) {
232 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
233 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
234 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000235 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000236 if (C == AndRHS) { // Masking out bits shifted in.
237 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
238 // Make the argument unsigned.
239 Value *ShVal = Op->getOperand(0);
240 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
241 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
242 }
243 }
244 break;
245 }
Craig Topperf40110f2014-04-25 05:29:35 +0000246 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000247}
248
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000249/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000250/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
251/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000252Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000253 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000254 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000255 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000256
Sanjay Patel85d79742016-08-31 19:49:56 +0000257 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000258 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000259 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000260
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000261 // V >= Min && V < Hi --> V < Hi
262 // V < Min || V >= Hi --> V >= Hi
263 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000264 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000265 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000266 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000267 }
268
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000269 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
270 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000271 Value *VMinusLo =
272 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
273 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000274 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000275}
276
Sanjay Patel77bf6222017-04-03 16:53:12 +0000277/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
278/// that can be simplified.
279/// One of A and B is considered the mask. The other is the value. This is
280/// described as the "AMask" or "BMask" part of the enum. If the enum contains
281/// only "Mask", then both A and B can be considered masks. If A is the mask,
282/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
283/// If both A and C are constants, this proof is also easy.
284/// For the following explanations, we assume that A is the mask.
285///
286/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
287/// bits of A are set in B.
288/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
289///
290/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
291/// bits of A are cleared in B.
292/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
293///
294/// "Mixed" declares that (A & B) == C and C might or might not contain any
295/// number of one bits and zero bits.
296/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
297///
298/// "Not" means that in above descriptions "==" should be replaced by "!=".
299/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
300///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000301/// If the mask A contains a single bit, then the following is equivalent:
302/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
303/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
304enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000305 AMask_AllOnes = 1,
306 AMask_NotAllOnes = 2,
307 BMask_AllOnes = 4,
308 BMask_NotAllOnes = 8,
309 Mask_AllZeros = 16,
310 Mask_NotAllZeros = 32,
311 AMask_Mixed = 64,
312 AMask_NotMixed = 128,
313 BMask_Mixed = 256,
314 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000315};
316
Sanjay Patel77bf6222017-04-03 16:53:12 +0000317/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
318/// satisfies.
319static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
320 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000321 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
322 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
323 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000324 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
325 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
326 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
327 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000328 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000329 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000330 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
331 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
332 if (IsAPow2)
333 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
334 : (AMask_AllOnes | AMask_Mixed));
335 if (IsBPow2)
336 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
337 : (BMask_AllOnes | BMask_Mixed));
338 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000339 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000340
Owen Anderson3fe002d2010-09-08 22:16:17 +0000341 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000342 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
343 : (AMask_NotAllOnes | AMask_NotMixed));
344 if (IsAPow2)
345 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
346 : (Mask_AllZeros | AMask_Mixed));
347 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
348 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000349 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000350
Craig Topperae48cb22012-12-20 07:15:54 +0000351 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000352 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
353 : (BMask_NotAllOnes | BMask_NotMixed));
354 if (IsBPow2)
355 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
356 : (Mask_AllZeros | BMask_Mixed));
357 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
358 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000359 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000360
361 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000362}
363
Tim Northoverc0756c42013-09-04 11:57:13 +0000364/// Convert an analysis of a masked ICmp into its equivalent if all boolean
365/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
366/// is adjacent to the corresponding normal flag (recording ==), this just
367/// involves swapping those bits over.
368static unsigned conjugateICmpMask(unsigned Mask) {
369 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000370 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
371 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000372 << 1;
373
Sanjay Patel77bf6222017-04-03 16:53:12 +0000374 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
375 AMask_NotMixed | BMask_NotMixed))
376 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000377
378 return NewMask;
379}
380
Sanjay Patel77bf6222017-04-03 16:53:12 +0000381/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
382/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
383/// RHS satisfy.
384static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
385 Value *&D, Value *&E, ICmpInst *LHS,
386 ICmpInst *RHS,
387 ICmpInst::Predicate &PredL,
388 ICmpInst::Predicate &PredR) {
389 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
390 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000391 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000392 if (LHS->getOperand(0)->getType()->isVectorTy())
393 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000394
395 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000396 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000397 // and L11 & L12 == L21 & L22. The same goes for RHS.
398 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000399 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000400 // above.
401 Value *L1 = LHS->getOperand(0);
402 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000403 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000404 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000405 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000406 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000407 } else {
408 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000409 if (!L1->getType()->isIntegerTy()) {
410 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000411 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000412 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
413 // Any icmp can be viewed as being trivially masked; if it allows us to
414 // remove one, it's worth it.
415 L11 = L1;
416 L12 = Constant::getAllOnesValue(L1->getType());
417 }
418
419 if (!L2->getType()->isIntegerTy()) {
420 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000421 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000422 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
423 L21 = L2;
424 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000425 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000426 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000427
428 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000429 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000430 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000431
432 Value *R1 = RHS->getOperand(0);
433 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000434 Value *R11, *R12;
435 bool Ok = false;
436 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000437 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000438 A = R11;
439 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000440 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000441 A = R12;
442 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000443 } else {
444 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000445 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000446 E = R2;
447 R1 = nullptr;
448 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000449 } else if (R1->getType()->isIntegerTy()) {
450 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
451 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000452 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000453 R11 = R1;
454 R12 = Constant::getAllOnesValue(R1->getType());
455 }
456
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000457 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000458 A = R11;
459 D = R12;
460 E = R2;
461 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000462 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000463 A = R12;
464 D = R11;
465 E = R2;
466 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000467 }
468 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000469
470 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000471 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000472 return 0;
473
Chad Rosier58919cc2016-05-09 21:37:43 +0000474 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000475 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000476 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
477 R11 = R2;
478 R12 = Constant::getAllOnesValue(R2->getType());
479 }
480
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000481 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000482 A = R11;
483 D = R12;
484 E = R1;
485 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000486 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000487 A = R12;
488 D = R11;
489 E = R1;
490 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000491 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000492 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000493 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000494 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000495 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000496 return 0;
497
498 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000499 B = L12;
500 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000501 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000502 B = L11;
503 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000504 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000505 B = L22;
506 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000507 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000508 B = L21;
509 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000510 }
511
Sanjay Patel77bf6222017-04-03 16:53:12 +0000512 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
513 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000514 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000515}
Sanjay Patel18549272015-09-08 18:24:36 +0000516
517/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
518/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000519static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
520 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000521 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000522 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
523 unsigned Mask =
524 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
525 if (Mask == 0)
526 return nullptr;
527
528 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
529 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000530
Tim Northoverc0756c42013-09-04 11:57:13 +0000531 // In full generality:
532 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
533 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
534 //
535 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
536 // equivalent to (icmp (A & X) !Op Y).
537 //
538 // Therefore, we can pretend for the rest of this function that we're dealing
539 // with the conjunction, provided we flip the sense of any comparisons (both
540 // input and output).
541
542 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000543 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000544 if (!IsAnd) {
545 // Convert the masking analysis into its equivalent with negated
546 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000547 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000548 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000549
Sanjay Patel77bf6222017-04-03 16:53:12 +0000550 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000551 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000552 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000553 Value *NewOr = Builder->CreateOr(B, D);
554 Value *NewAnd = Builder->CreateAnd(A, NewOr);
555 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000556 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000557 // with B and D, having a single bit set.
558 Value *Zero = Constant::getNullValue(A->getType());
559 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000561 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000562 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000563 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000564 Value *NewOr = Builder->CreateOr(B, D);
565 Value *NewAnd = Builder->CreateAnd(A, NewOr);
566 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000567 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000568 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000569 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000570 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000571 Value *NewAnd1 = Builder->CreateAnd(B, D);
572 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
573 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000574 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000575
576 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000577 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000578 // easy cases for now" decision.
579 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000580 if (!BCst)
581 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000582 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000583 if (!DCst)
584 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000585
Sanjay Patel77bf6222017-04-03 16:53:12 +0000586 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000587 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
588 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
589 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
590 // Only valid if one of the masks is a superset of the other (check "B&D" is
591 // the same as either B or D).
592 APInt NewMask = BCst->getValue() & DCst->getValue();
593
594 if (NewMask == BCst->getValue())
595 return LHS;
596 else if (NewMask == DCst->getValue())
597 return RHS;
598 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000599
600 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000601 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
602 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
603 // Only valid if one of the masks is a superset of the other (check "B|D" is
604 // the same as either B or D).
605 APInt NewMask = BCst->getValue() | DCst->getValue();
606
607 if (NewMask == BCst->getValue())
608 return LHS;
609 else if (NewMask == DCst->getValue())
610 return RHS;
611 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000612
613 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000614 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000615 // We already know that B & C == C && D & E == E.
616 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
617 // C and E, which are shared by both the mask B and the mask D, don't
618 // contradict, then we can transform to
619 // -> (icmp eq (A & (B|D)), (C|E))
620 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000621 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000622 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000623 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000624 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000625 if (!CCst)
626 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000627 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000628 if (!ECst)
629 return nullptr;
630 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000631 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000632 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000633 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000634
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000635 // If there is a conflict, we should actually return a false for the
636 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000637 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000638 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000639 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000640
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000641 Value *NewOr1 = Builder->CreateOr(B, D);
642 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
643 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
644 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000645 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000646
Craig Topperf40110f2014-04-25 05:29:35 +0000647 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000648}
649
Erik Ecksteind1817522014-12-03 10:39:15 +0000650/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
651/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
652/// If \p Inverted is true then the check is for the inverted range, e.g.
653/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
654Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
655 bool Inverted) {
656 // Check the lower range comparison, e.g. x >= 0
657 // InstCombine already ensured that if there is a constant it's on the RHS.
658 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
659 if (!RangeStart)
660 return nullptr;
661
662 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
663 Cmp0->getPredicate());
664
665 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
666 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
667 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
668 return nullptr;
669
670 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
671 Cmp1->getPredicate());
672
673 Value *Input = Cmp0->getOperand(0);
674 Value *RangeEnd;
675 if (Cmp1->getOperand(0) == Input) {
676 // For the upper range compare we have: icmp x, n
677 RangeEnd = Cmp1->getOperand(1);
678 } else if (Cmp1->getOperand(1) == Input) {
679 // For the upper range compare we have: icmp n, x
680 RangeEnd = Cmp1->getOperand(0);
681 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
682 } else {
683 return nullptr;
684 }
685
686 // Check the upper range comparison, e.g. x < n
687 ICmpInst::Predicate NewPred;
688 switch (Pred1) {
689 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
690 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
691 default: return nullptr;
692 }
693
694 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000695 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
696 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000697 return nullptr;
698
699 if (Inverted)
700 NewPred = ICmpInst::getInversePredicate(NewPred);
701
702 return Builder->CreateICmp(NewPred, Input, RangeEnd);
703}
704
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000705static Value *
706foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
707 bool JoinedByAnd,
708 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000709 Value *X = LHS->getOperand(0);
710 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000711 return nullptr;
712
Sanjay Patelef9f5862017-04-15 17:55:06 +0000713 const APInt *C1, *C2;
714 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
715 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000716 return nullptr;
717
718 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
719 ICmpInst::Predicate Pred = LHS->getPredicate();
720 if (Pred != RHS->getPredicate())
721 return nullptr;
722 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
723 return nullptr;
724 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
725 return nullptr;
726
727 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000728 if (C1->ugt(*C2))
729 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000730
Sanjay Patelef9f5862017-04-15 17:55:06 +0000731 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000732 if (Xor.isPowerOf2()) {
733 // If LHSC and RHSC differ by only one bit, then set that bit in X and
734 // compare against the larger constant:
735 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
736 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
737 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
738 // 'and' because that may lead to smaller codegen from a smaller constant.
739 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000740 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000741 }
742
743 // Special case: get the ordering right when the values wrap around zero.
744 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000745 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000746 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000747
Sanjay Patelef9f5862017-04-15 17:55:06 +0000748 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000749 // (X == 13 || X == 14) --> X - 13 <=u 1
750 // (X != 13 && X != 14) --> X - 13 >u 1
751 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000752 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000753 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
754 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
755 }
756
757 return nullptr;
758}
759
Craig Topperda6ea0d2017-06-16 05:10:37 +0000760// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
761// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
762Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
763 bool JoinedByAnd,
764 Instruction &CxtI) {
765 ICmpInst::Predicate Pred = LHS->getPredicate();
766 if (Pred != RHS->getPredicate())
767 return nullptr;
768 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
769 return nullptr;
770 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
771 return nullptr;
772
773 // TODO support vector splats
774 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
775 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
776 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
777 return nullptr;
778
779 Value *A, *B, *C, *D;
780 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
781 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
782 if (A == D || B == D)
783 std::swap(C, D);
784 if (B == C)
785 std::swap(A, B);
786
787 if (A == C &&
788 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
789 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
790 Value *Mask = Builder->CreateOr(B, D);
791 Value *Masked = Builder->CreateAnd(A, Mask);
792 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
793 return Builder->CreateICmp(NewPred, Masked, Mask);
794 }
795 }
796
797 return nullptr;
798}
799
Sanjay Patel18549272015-09-08 18:24:36 +0000800/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000801Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
802 Instruction &CxtI) {
803 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
804 // if K1 and K2 are a one-bit mask.
805 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
806 return V;
807
Sanjay Patel519a87a2017-04-05 17:38:34 +0000808 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000809
810 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000811 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000812 if (LHS->getOperand(0) == RHS->getOperand(1) &&
813 LHS->getOperand(1) == RHS->getOperand(0))
814 LHS->swapOperands();
815 if (LHS->getOperand(0) == RHS->getOperand(0) &&
816 LHS->getOperand(1) == RHS->getOperand(1)) {
817 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
818 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
819 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000820 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000821 }
822 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000823
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000824 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000825 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000826 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000827
Erik Ecksteind1817522014-12-03 10:39:15 +0000828 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
829 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
830 return V;
831
832 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
833 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
834 return V;
835
Sanjay Patelef9f5862017-04-15 17:55:06 +0000836 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
837 return V;
838
Chris Lattner0a8191e2010-01-05 07:50:36 +0000839 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000840 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000841 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
842 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
843 if (!LHSC || !RHSC)
844 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000845
Sanjay Patel519a87a2017-04-05 17:38:34 +0000846 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000847 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000848 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000849 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
851 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000852 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000853 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000854 }
855 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000856
Benjamin Kramer101720f2011-04-28 20:09:57 +0000857 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000858 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000859 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000860 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
861 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000862 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000863 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000864
865 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000866 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000867 if (match(RHS0, m_Trunc(m_Value(V))) &&
868 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000869 SmallC = RHSC;
870 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000871 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
872 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000873 SmallC = LHSC;
874 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000875 }
876
Sanjay Patel519a87a2017-04-05 17:38:34 +0000877 if (SmallC && BigC) {
878 unsigned BigBitSize = BigC->getType()->getBitWidth();
879 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000880
881 // Check that the low bits are zero.
882 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000883 if ((Low & AndC->getValue()).isNullValue() &&
884 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000885 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
886 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
887 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
888 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000889 }
890 }
891 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000892
Chris Lattner0a8191e2010-01-05 07:50:36 +0000893 // From here on, we only handle:
894 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000895 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000896 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000897
Sanjay Patel519a87a2017-04-05 17:38:34 +0000898 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
899 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
900 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
901 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
902 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000903 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000904
Chris Lattner0a8191e2010-01-05 07:50:36 +0000905 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000906 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000907 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000908
Chris Lattner0a8191e2010-01-05 07:50:36 +0000909 // Ensure that the larger constant is on the RHS.
910 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000911 if (CmpInst::isSigned(PredL) ||
912 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000913 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000914 else
915 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000916
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 if (ShouldSwap) {
918 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000919 std::swap(LHSC, RHSC);
920 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000921 }
922
Dan Gohman4a618822010-02-10 16:03:48 +0000923 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 // comparing a value against two constants and and'ing the result
925 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000926 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
927 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000928 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000929 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930
Sanjay Patel519a87a2017-04-05 17:38:34 +0000931 switch (PredL) {
932 default:
933 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000935 switch (PredR) {
936 default:
937 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000938 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000939 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000940 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000941 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000942 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000943 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000944 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000946 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000947 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000948 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000950 // Potential folds for this case should already be handled.
951 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 }
953 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000954 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000955 switch (PredR) {
956 default:
957 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000959 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000960 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000961 break; // (X u> 13 & X != 15) -> no change
962 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000963 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
964 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000965 }
966 break;
967 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000968 switch (PredR) {
969 default:
970 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000971 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000972 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000973 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000974 break; // (X s> 13 & X != 15) -> no change
975 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000976 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000977 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000978 }
979 break;
980 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000981
Craig Topperf40110f2014-04-25 05:29:35 +0000982 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000983}
984
Sanjay Patel18549272015-09-08 18:24:36 +0000985/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
986/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000987Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000988 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
989 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
990 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
991
992 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
993 // Swap RHS operands to match LHS.
994 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
995 std::swap(Op1LHS, Op1RHS);
996 }
997
998 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
999 // Suppose the relation between x and y is R, where R is one of
1000 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1001 // testing the desired relations.
1002 //
1003 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1004 // bool(R & CC0) && bool(R & CC1)
1005 // = bool((R & CC0) & (R & CC1))
1006 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1007 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1008 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1009 Builder);
1010
Chris Lattner0a8191e2010-01-05 07:50:36 +00001011 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1012 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001013 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001014 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001015
Chris Lattner0a8191e2010-01-05 07:50:36 +00001016 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1017 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1018 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1019 // If either of the constants are nans, then the whole thing returns
1020 // false.
1021 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001022 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001023 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001025
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 // Handle vector zeros. This occurs because the canonical form of
1027 // "fcmp ord x,x" is "fcmp ord x, 0".
1028 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1029 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001030 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001031 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001032 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001033
Craig Topperf40110f2014-04-25 05:29:35 +00001034 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001035}
1036
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001037/// Match De Morgan's Laws:
1038/// (~A & ~B) == (~(A | B))
1039/// (~A | ~B) == (~(A & B))
1040static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001041 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001042 auto Opcode = I.getOpcode();
1043 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1044 "Trying to match De Morgan's Laws with something other than and/or");
1045
Sanjay Patel7caaa792017-05-09 20:05:05 +00001046 // Flip the logic operation.
1047 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1048
1049 Value *A, *B;
1050 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1051 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1052 !IsFreeToInvert(A, A->hasOneUse()) &&
1053 !IsFreeToInvert(B, B->hasOneUse())) {
1054 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1055 return BinaryOperator::CreateNot(AndOr);
1056 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001057
1058 return nullptr;
1059}
1060
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001061bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1062 Value *CastSrc = CI->getOperand(0);
1063
1064 // Noop casts and casts of constants should be eliminated trivially.
1065 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1066 return false;
1067
1068 // If this cast is paired with another cast that can be eliminated, we prefer
1069 // to have it eliminated.
1070 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1071 if (isEliminableCastPair(PrecedingCI, CI))
1072 return false;
1073
1074 // If this is a vector sext from a compare, then we don't want to break the
1075 // idiom where each element of the extended vector is either zero or all ones.
1076 if (CI->getOpcode() == Instruction::SExt &&
1077 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1078 return false;
1079
1080 return true;
1081}
1082
Sanjay Patel60312bc42016-09-12 00:16:23 +00001083/// Fold {and,or,xor} (cast X), C.
1084static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1085 InstCombiner::BuilderTy *Builder) {
1086 Constant *C;
1087 if (!match(Logic.getOperand(1), m_Constant(C)))
1088 return nullptr;
1089
1090 auto LogicOpc = Logic.getOpcode();
1091 Type *DestTy = Logic.getType();
1092 Type *SrcTy = Cast->getSrcTy();
1093
Sanjay Pateld1e81192017-06-22 15:46:54 +00001094 // Move the logic operation ahead of a zext if the constant is unchanged in
1095 // the smaller source type. Performing the logic in a smaller type may provide
1096 // more information to later folds, and the smaller logic instruction may be
1097 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001098 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001099 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1100 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1101 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1102 if (ZextTruncC == C) {
1103 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1104 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1105 return new ZExtInst(NewOp, DestTy);
1106 }
1107 }
1108
1109 return nullptr;
1110}
1111
1112/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001113Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001114 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001115 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001116
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001118 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001119 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001120 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001121
Sanjay Patel9bba7502016-03-03 19:19:04 +00001122 // This must be a cast from an integer or integer vector source type to allow
1123 // transformation of the logic operation to the source type.
1124 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001125 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001126 if (!SrcTy->isIntOrIntVectorTy())
1127 return nullptr;
1128
Sanjay Patel60312bc42016-09-12 00:16:23 +00001129 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1130 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001131
Sanjay Patel9bba7502016-03-03 19:19:04 +00001132 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1133 if (!Cast1)
1134 return nullptr;
1135
1136 // Both operands of the logic operation are casts. The casts must be of the
1137 // same type for reduction.
1138 auto CastOpcode = Cast0->getOpcode();
1139 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001140 return nullptr;
1141
1142 Value *Cast0Src = Cast0->getOperand(0);
1143 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001144
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001145 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001146 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001147 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1148 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001149 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001150 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001151
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001152 // For now, only 'and'/'or' have optimizations after this.
1153 if (LogicOpc == Instruction::Xor)
1154 return nullptr;
1155
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001156 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001157 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001158 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1159 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1160 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001161 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001162 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001163 if (Res)
1164 return CastInst::Create(CastOpcode, Res, DestTy);
1165 return nullptr;
1166 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001167
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001168 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001169 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001170 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1171 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1172 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001173 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1174 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001175 if (Res)
1176 return CastInst::Create(CastOpcode, Res, DestTy);
1177 return nullptr;
1178 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001179
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001180 return nullptr;
1181}
1182
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001183static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1185
1186 // Canonicalize SExt or Not to the LHS
1187 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1188 std::swap(Op0, Op1);
1189 }
1190
1191 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1192 Value *X = nullptr;
1193 if (match(Op0, m_SExt(m_Value(X))) &&
1194 X->getType()->getScalarType()->isIntegerTy(1)) {
1195 Value *Zero = Constant::getNullValue(Op1->getType());
1196 return SelectInst::Create(X, Op1, Zero);
1197 }
1198
1199 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1200 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1201 X->getType()->getScalarType()->isIntegerTy(1)) {
1202 Value *Zero = Constant::getNullValue(Op0->getType());
1203 return SelectInst::Create(X, Zero, Op1);
1204 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001205
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001206 return nullptr;
1207}
1208
Sanjay Patele0c26e02017-04-23 22:00:02 +00001209static Instruction *foldAndToXor(BinaryOperator &I,
1210 InstCombiner::BuilderTy &Builder) {
1211 assert(I.getOpcode() == Instruction::And);
1212 Value *Op0 = I.getOperand(0);
1213 Value *Op1 = I.getOperand(1);
1214 Value *A, *B;
1215
1216 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1217 // (A | B) & ~(A & B) --> A ^ B
1218 // (A | B) & ~(B & A) --> A ^ B
1219 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1220 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1221 return BinaryOperator::CreateXor(A, B);
1222
1223 // (A | ~B) & (~A | B) --> ~(A ^ B)
1224 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1225 // (~B | A) & (~A | B) --> ~(A ^ B)
1226 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001227 if (Op0->hasOneUse() || Op1->hasOneUse())
1228 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1229 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1230 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001231
1232 return nullptr;
1233}
1234
1235static Instruction *foldOrToXor(BinaryOperator &I,
1236 InstCombiner::BuilderTy &Builder) {
1237 assert(I.getOpcode() == Instruction::Or);
1238 Value *Op0 = I.getOperand(0);
1239 Value *Op1 = I.getOperand(1);
1240 Value *A, *B;
1241
1242 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1243 // (A & B) | ~(A | B) --> ~(A ^ B)
1244 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001245 if (Op0->hasOneUse() || Op1->hasOneUse())
1246 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1247 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1248 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001249
1250 // (A & ~B) | (~A & B) --> A ^ B
1251 // (A & ~B) | (B & ~A) --> A ^ B
1252 // (~B & A) | (~A & B) --> A ^ B
1253 // (~B & A) | (B & ~A) --> A ^ B
1254 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1255 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1256 return BinaryOperator::CreateXor(A, B);
1257
1258 return nullptr;
1259}
1260
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001261// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1262// here. We should standardize that construct where it is needed or choose some
1263// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001264Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001265 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1267
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001268 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001269 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001270
Craig Toppera4205622017-06-09 03:21:29 +00001271 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001272 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273
Craig Topper9d4171a2012-12-20 07:09:41 +00001274 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001275 // purpose is to compute bits we don't care about.
1276 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001277 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001278
Sanjay Patele0c26e02017-04-23 22:00:02 +00001279 // Do this before using distributive laws to catch simple and/or/not patterns.
1280 if (Instruction *Xor = foldAndToXor(I, *Builder))
1281 return Xor;
1282
1283 // (A|B)&(A|C) -> A|(B&C) etc
1284 if (Value *V = SimplifyUsingDistributiveLaws(I))
1285 return replaceInstUsesWith(I, V);
1286
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001287 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001288 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001289
Chris Lattner0a8191e2010-01-05 07:50:36 +00001290 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1291 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001292
1293 // Optimize a variety of ((val OP C1) & C2) combinations...
1294 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1295 Value *Op0LHS = Op0I->getOperand(0);
1296 Value *Op0RHS = Op0I->getOperand(1);
1297 switch (Op0I->getOpcode()) {
1298 default: break;
1299 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001300 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001301 // If the mask is only needed on one incoming arm, push it up.
1302 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001303
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001304 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001305 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001306 // Not masking anything out for the LHS, move to RHS.
1307 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1308 Op0RHS->getName()+".masked");
1309 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1310 }
1311 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001312 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001313 // Not masking anything out for the RHS, move to LHS.
1314 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1315 Op0LHS->getName()+".masked");
1316 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1317 }
1318
1319 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001320 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001321 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001322 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001323 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001324 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1325
Chris Lattner0a8191e2010-01-05 07:50:36 +00001326 break;
1327
1328 case Instruction::Shl:
1329 case Instruction::LShr:
1330 // (1 << x) & 1 --> zext(x == 0)
1331 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001332 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 Value *NewICmp =
1334 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1335 return new ZExtInst(NewICmp, I.getType());
1336 }
1337 break;
1338 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001339
David Majnemerde55c602017-01-17 18:08:06 +00001340 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1341 // of X and OP behaves well when given trunc(C1) and X.
1342 switch (Op0I->getOpcode()) {
1343 default:
1344 break;
1345 case Instruction::Xor:
1346 case Instruction::Or:
1347 case Instruction::Mul:
1348 case Instruction::Add:
1349 case Instruction::Sub:
1350 Value *X;
1351 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001352 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001353 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1354 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1355 Value *BinOp;
1356 if (isa<ZExtInst>(Op0LHS))
1357 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1358 else
1359 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1360 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1361 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1362 return new ZExtInst(And, I.getType());
1363 }
1364 }
1365 }
1366
Chris Lattner0a8191e2010-01-05 07:50:36 +00001367 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1368 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1369 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001370 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001371
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001372 // If this is an integer truncation, and if the source is an 'and' with
1373 // immediate, transform it. This frequently occurs for bitfield accesses.
1374 {
Craig Topperf40110f2014-04-25 05:29:35 +00001375 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001376 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1377 // Change: and (trunc (and X, YC) to T), C2
1378 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001379 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001380 // other simplifications.
1381 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1382 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1383 C3 = ConstantExpr::getAnd(C3, AndRHS);
1384 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 }
1386 }
Craig Topper86173602017-04-04 20:26:25 +00001387 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001388
Craig Topper86173602017-04-04 20:26:25 +00001389 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001390 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1391 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392
Sanjay Patel7caaa792017-05-09 20:05:05 +00001393 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001394 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001395
Chris Lattner0a8191e2010-01-05 07:50:36 +00001396 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001397 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001398 // A&(A^B) => A & ~B
1399 {
1400 Value *tmpOp0 = Op0;
1401 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001402 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001403 if (A == Op1 || B == Op1 ) {
1404 tmpOp1 = Op0;
1405 tmpOp0 = Op1;
1406 // Simplify below
1407 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001410 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001411 if (B == tmpOp0) {
1412 std::swap(A, B);
1413 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001414 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001415 // A is originally -1 (or a vector of -1 and undefs), then we enter
1416 // an endless loop. By checking that A is non-constant we ensure that
1417 // we will never get to the loop.
1418 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001419 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001420 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001421 }
1422
1423 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001424 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001425 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001426 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001427 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001428
1429 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1430 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1431 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001432 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001433 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1434
1435 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1436 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1437 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001438 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001439 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001440
1441 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001442 // (A | B) & (B ^ (~A)) -> (A & B)
1443 // (B | A) & ((~A) ^ B) -> (A & B)
1444 // (B | A) & (B ^ (~A)) -> (A & B)
1445 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1446 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001447 return BinaryOperator::CreateAnd(A, B);
1448
1449 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001450 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001451 // (B ^ (~A)) & (A | B) -> (A & B)
1452 // (B ^ (~A)) & (B | A) -> (A & B)
1453 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001454 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001455 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001456 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001457
David Majnemer5e96f1b2014-08-30 06:18:20 +00001458 {
1459 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1460 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1461 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001462 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001463 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001464
David Majnemer5e96f1b2014-08-30 06:18:20 +00001465 // TODO: Make this recursive; it's a little tricky because an arbitrary
1466 // number of 'and' instructions might have to be created.
1467 Value *X, *Y;
1468 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1469 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001470 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001472 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001473 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001474 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001475 }
1476 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1477 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001478 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001480 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001481 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001482 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001483 }
1484 }
1485
Chris Lattner4e8137d2010-02-11 06:26:33 +00001486 // If and'ing two fcmp, try combine them into one.
1487 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1488 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001489 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001490 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001491
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001492 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1493 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001494
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001495 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1496 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001497
Craig Topperf40110f2014-04-25 05:29:35 +00001498 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001499}
1500
Chad Rosiera00df492016-05-25 16:22:14 +00001501/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1502/// insert the new intrinsic and return it.
1503Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001504 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1505
1506 // Look through zero extends.
1507 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1508 Op0 = Ext->getOperand(0);
1509
1510 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1511 Op1 = Ext->getOperand(0);
1512
1513 // (A | B) | C and A | (B | C) -> bswap if possible.
1514 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1515 match(Op1, m_Or(m_Value(), m_Value()));
1516
1517 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1518 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1519 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1520
1521 // (A & B) | (C & D) -> bswap if possible.
1522 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1523 match(Op1, m_And(m_Value(), m_Value()));
1524
1525 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1526 return nullptr;
1527
James Molloyf01488e2016-01-15 09:20:19 +00001528 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001529 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001530 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001531 Instruction *LastInst = Insts.pop_back_val();
1532 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001533
James Molloyf01488e2016-01-15 09:20:19 +00001534 for (auto *Inst : Insts)
1535 Worklist.Add(Inst);
1536 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001537}
1538
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001539/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1540static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1541 unsigned NumElts = C1->getType()->getVectorNumElements();
1542 for (unsigned i = 0; i != NumElts; ++i) {
1543 Constant *EltC1 = C1->getAggregateElement(i);
1544 Constant *EltC2 = C2->getAggregateElement(i);
1545 if (!EltC1 || !EltC2)
1546 return false;
1547
1548 // One element must be all ones, and the other must be all zeros.
1549 // FIXME: Allow undef elements.
1550 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1551 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1552 return false;
1553 }
1554 return true;
1555}
1556
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001557/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1558/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1559/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001560static Value *getSelectCondition(Value *A, Value *B,
1561 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001562 // If these are scalars or vectors of i1, A can be used directly.
1563 Type *Ty = A->getType();
1564 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1565 return A;
1566
1567 // If A and B are sign-extended, look through the sexts to find the booleans.
1568 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001569 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001570 if (match(A, m_SExt(m_Value(Cond))) &&
1571 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001572 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1573 NotB = peekThroughBitcast(NotB, true);
1574 if (match(NotB, m_SExt(m_Specific(Cond))))
1575 return Cond;
1576 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001577
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001578 // All scalar (and most vector) possibilities should be handled now.
1579 // Try more matches that only apply to non-splat constant vectors.
1580 if (!Ty->isVectorTy())
1581 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001582
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001583 // If both operands are constants, see if the constants are inverse bitmasks.
1584 Constant *AC, *BC;
1585 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1586 areInverseVectorBitmasks(AC, BC))
1587 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1588
1589 // If both operands are xor'd with constants using the same sexted boolean
1590 // operand, see if the constants are inverse bitmasks.
1591 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1592 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1593 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1594 areInverseVectorBitmasks(AC, BC)) {
1595 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1596 return Builder.CreateXor(Cond, AC);
1597 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001598 return nullptr;
1599}
1600
1601/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1602/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001603static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001604 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001605 // The potential condition of the select may be bitcasted. In that case, look
1606 // through its bitcast and the corresponding bitcast of the 'not' condition.
1607 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001608 A = peekThroughBitcast(A, true);
1609 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001610
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001611 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001612 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001613 // The bitcasts will either all exist or all not exist. The builder will
1614 // not create unnecessary casts if the types already match.
1615 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1616 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1617 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1618 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001619 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001620
Craig Topperf40110f2014-04-25 05:29:35 +00001621 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001622}
1623
Sanjay Patel18549272015-09-08 18:24:36 +00001624/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001625Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001626 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001627 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1628 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001629 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1630 return V;
1631
1632 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1633
Sanjay Patel519a87a2017-04-05 17:38:34 +00001634 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1635 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001636
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001637 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1638 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1639 // The original condition actually refers to the following two ranges:
1640 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1641 // We can fold these two ranges if:
1642 // 1) C1 and C2 is unsigned greater than C3.
1643 // 2) The two ranges are separated.
1644 // 3) C1 ^ C2 is one-bit mask.
1645 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1646 // This implies all values in the two ranges differ by exactly one bit.
1647
Sanjay Patel519a87a2017-04-05 17:38:34 +00001648 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1649 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1650 LHSC->getType() == RHSC->getType() &&
1651 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001652
1653 Value *LAdd = LHS->getOperand(0);
1654 Value *RAdd = RHS->getOperand(0);
1655
1656 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001657 ConstantInt *LAddC, *RAddC;
1658 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1659 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1660 LAddC->getValue().ugt(LHSC->getValue()) &&
1661 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001662
Sanjay Patel519a87a2017-04-05 17:38:34 +00001663 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1664 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1665 ConstantInt *MaxAddC = nullptr;
1666 if (LAddC->getValue().ult(RAddC->getValue()))
1667 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001668 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001669 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001670
Sanjay Patel519a87a2017-04-05 17:38:34 +00001671 APInt RRangeLow = -RAddC->getValue();
1672 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1673 APInt LRangeLow = -LAddC->getValue();
1674 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001675 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1676 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1677 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1678 : RRangeLow - LRangeLow;
1679
1680 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001681 RangeDiff.ugt(LHSC->getValue())) {
1682 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001683
Sanjay Patel519a87a2017-04-05 17:38:34 +00001684 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1685 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1686 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001687 }
1688 }
1689 }
1690 }
1691
Chris Lattner0a8191e2010-01-05 07:50:36 +00001692 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001693 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001694 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1695 LHS->getOperand(1) == RHS->getOperand(0))
1696 LHS->swapOperands();
1697 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1698 LHS->getOperand(1) == RHS->getOperand(1)) {
1699 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1700 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1701 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001702 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001703 }
1704 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001705
1706 // handle (roughly):
1707 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001708 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001709 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001710
Sanjay Patele4159d22017-04-10 19:38:36 +00001711 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001712 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1713 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1714 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001715 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001716 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001717 B = LHS0;
1718 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1719 A = RHS0;
1720 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001721 A = RHS->getOperand(1);
1722 }
1723 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1724 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001725 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001726 B = RHS0;
1727 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1728 A = LHS0;
1729 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001730 A = LHS->getOperand(1);
1731 }
1732 if (A && B)
1733 return Builder->CreateICmp(
1734 ICmpInst::ICMP_UGE,
1735 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1736 }
1737
Erik Ecksteind1817522014-12-03 10:39:15 +00001738 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1739 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1740 return V;
1741
1742 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1743 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1744 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001745
Sanjay Patelef9f5862017-04-15 17:55:06 +00001746 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1747 return V;
1748
David Majnemerc2a990b2013-07-05 00:31:17 +00001749 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001750 if (!LHSC || !RHSC)
1751 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001752
Sanjay Patel519a87a2017-04-05 17:38:34 +00001753 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001754 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001755 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001756 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001757 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001758 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001759 }
1760
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001761 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001762 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001763 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1764 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001765 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001766 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001767 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001768 }
1769
Chris Lattner0a8191e2010-01-05 07:50:36 +00001770 // From here on, we only handle:
1771 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001772 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001773 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001774
Sanjay Patel519a87a2017-04-05 17:38:34 +00001775 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1776 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1777 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1778 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1779 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001780 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001781
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001783 if (!PredicatesFoldable(PredL, PredR))
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 // Ensure that the larger constant is on the RHS.
1787 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001788 if (CmpInst::isSigned(PredL) ||
1789 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001790 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001791 else
1792 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001793
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794 if (ShouldSwap) {
1795 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001796 std::swap(LHSC, RHSC);
1797 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001798 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001799
Dan Gohman4a618822010-02-10 16:03:48 +00001800 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001801 // comparing a value against two constants and or'ing the result
1802 // together. Because of the above check, we know that we only have
1803 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1804 // icmp folding check above), that the two constants are not
1805 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001806 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001807
Sanjay Patel519a87a2017-04-05 17:38:34 +00001808 switch (PredL) {
1809 default:
1810 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001812 switch (PredR) {
1813 default:
1814 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001815 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001816 // Potential folds for this case should already be handled.
1817 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001818 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1819 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001820 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 }
1822 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001824 switch (PredR) {
1825 default:
1826 llvm_unreachable("Unknown integer condition code!");
1827 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001828 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001829 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001830 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001831 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1832 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001833 }
1834 break;
1835 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001836 switch (PredR) {
1837 default:
1838 llvm_unreachable("Unknown integer condition code!");
1839 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001840 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001841 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001842 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001843 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001844 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001845 }
1846 break;
1847 }
Craig Topperf40110f2014-04-25 05:29:35 +00001848 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001849}
1850
Sanjay Patel18549272015-09-08 18:24:36 +00001851/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1852/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001853Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001854 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1855 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1856 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1857
1858 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1859 // Swap RHS operands to match LHS.
1860 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1861 std::swap(Op1LHS, Op1RHS);
1862 }
1863
1864 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1865 // This is a similar transformation to the one in FoldAndOfFCmps.
1866 //
1867 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1868 // bool(R & CC0) || bool(R & CC1)
1869 // = bool((R & CC0) | (R & CC1))
1870 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1871 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1872 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1873 Builder);
1874
Chris Lattner0a8191e2010-01-05 07:50:36 +00001875 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001876 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1878 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1879 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1880 // If either of the constants are nans, then the whole thing returns
1881 // true.
1882 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001883 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001884
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 // Otherwise, no need to compare the two constants, compare the
1886 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001887 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001888 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001889
Chris Lattner0a8191e2010-01-05 07:50:36 +00001890 // Handle vector zeros. This occurs because the canonical form of
1891 // "fcmp uno x,x" is "fcmp uno x, 0".
1892 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1893 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001894 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001895
Craig Topperf40110f2014-04-25 05:29:35 +00001896 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001898
Craig Topperf40110f2014-04-25 05:29:35 +00001899 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001900}
1901
Sanjay Patel18549272015-09-08 18:24:36 +00001902/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001903///
1904/// ((A | B) & C1) | (B & C2)
1905///
1906/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001907///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908/// (A & C1) | B
1909///
1910/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001911static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1912 Value *A, Value *B, Value *C,
1913 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001914 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001915 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001916
Craig Topperf40110f2014-04-25 05:29:35 +00001917 Value *V1 = nullptr;
1918 ConstantInt *CI2 = nullptr;
1919 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001920
1921 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001922 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001923
1924 if (V1 == A || V1 == B) {
1925 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1926 return BinaryOperator::CreateOr(NewOp, V1);
1927 }
1928
Craig Topperf40110f2014-04-25 05:29:35 +00001929 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001930}
1931
David Majnemer5d1aeba2014-08-21 05:14:48 +00001932/// \brief This helper function folds:
1933///
Craig Toppera074c102017-06-21 18:57:00 +00001934/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001935///
1936/// into:
1937///
1938/// (A & C1) ^ B
1939///
1940/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001941static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1942 Value *A, Value *B, Value *C,
1943 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001944 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1945 if (!CI1)
1946 return nullptr;
1947
1948 Value *V1 = nullptr;
1949 ConstantInt *CI2 = nullptr;
1950 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1951 return nullptr;
1952
1953 APInt Xor = CI1->getValue() ^ CI2->getValue();
1954 if (!Xor.isAllOnesValue())
1955 return nullptr;
1956
1957 if (V1 == A || V1 == B) {
1958 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1959 return BinaryOperator::CreateXor(NewOp, V1);
1960 }
1961
1962 return nullptr;
1963}
1964
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001965// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1966// here. We should standardize that construct where it is needed or choose some
1967// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001969 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1971
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001972 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001973 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001974
Craig Toppera4205622017-06-09 03:21:29 +00001975 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001976 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001977
Craig Topper9d4171a2012-12-20 07:09:41 +00001978 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001979 // purpose is to compute bits we don't care about.
1980 if (SimplifyDemandedInstructionBits(I))
1981 return &I;
1982
Sanjay Patele0c26e02017-04-23 22:00:02 +00001983 // Do this before using distributive laws to catch simple and/or/not patterns.
1984 if (Instruction *Xor = foldOrToXor(I, *Builder))
1985 return Xor;
1986
1987 // (A&B)|(A&C) -> A&(B|C) etc
1988 if (Value *V = SimplifyUsingDistributiveLaws(I))
1989 return replaceInstUsesWith(I, V);
1990
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001991 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001992 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001993
Craig Topper86173602017-04-04 20:26:25 +00001994 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001995 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1996 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001997
Chad Rosiere5819e22016-05-26 14:58:51 +00001998 // Given an OR instruction, check to see if this is a bswap.
1999 if (Instruction *BSwap = MatchBSwap(I))
2000 return BSwap;
2001
Craig Topperafa07c52017-04-09 06:12:41 +00002002 {
2003 Value *A;
2004 const APInt *C;
2005 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2006 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2007 MaskedValueIsZero(Op1, *C, 0, &I)) {
2008 Value *NOr = Builder->CreateOr(A, Op1);
2009 NOr->takeName(Op0);
2010 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002011 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002012 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002013
Craig Topperafa07c52017-04-09 06:12:41 +00002014 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2015 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2016 MaskedValueIsZero(Op0, *C, 0, &I)) {
2017 Value *NOr = Builder->CreateOr(A, Op0);
2018 NOr->takeName(Op0);
2019 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002020 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002021 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002022 }
2023
Craig Topperafa07c52017-04-09 06:12:41 +00002024 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025
Suyog Sardad64faf62014-07-22 18:09:41 +00002026 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002027 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2028 return BinaryOperator::CreateOr(A, Op1);
2029 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2030 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002031
2032 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002033 // The NOT is guaranteed to be in the RHS by complexity ordering.
2034 if (match(Op1, m_Not(m_Value(A))) &&
2035 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2036 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002037
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002039 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002040 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2041 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002042 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002043 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2044 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002045 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002046 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002047 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002048 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002049 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002050 ((V1 == B &&
2051 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2052 (V2 == B &&
2053 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002054 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002055 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002056 // Or commutes, try both ways.
2057 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002058 ((V1 == A &&
2059 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2060 (V2 == A &&
2061 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002062 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002063 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002064
Chris Lattner95188692010-01-11 06:55:24 +00002065 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002066 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002067 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002068 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002069 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002070 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002071 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002072 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2073 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002074 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002075 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002076 }
2077 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002078
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002079 // Don't try to form a select if it's unlikely that we'll get rid of at
2080 // least one of the operands. A select is generally more expensive than the
2081 // 'or' that it is replacing.
2082 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2083 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2084 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2085 return replaceInstUsesWith(I, V);
2086 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2087 return replaceInstUsesWith(I, V);
2088 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2089 return replaceInstUsesWith(I, V);
2090 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2097 return replaceInstUsesWith(I, V);
2098 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2099 return replaceInstUsesWith(I, V);
2100 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101
Benjamin Kramer11743242010-07-12 13:34:22 +00002102 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002103 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2104 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2105 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002106 }
2107 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002108 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2109 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2110 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002111 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002112 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002113 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2114 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2115 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002116 }
2117 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002118 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2119 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2120 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002121 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002122 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002123
David Majnemer42af3602014-07-30 21:26:37 +00002124 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2125 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2126 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002127 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002128
2129 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2130 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2131 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002132 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002133
David Majnemerf1eda232014-08-14 06:41:38 +00002134 // ((B | C) & A) | B -> B | (A & C)
2135 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2136 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2137
Sanjay Patel7caaa792017-05-09 20:05:05 +00002138 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002139 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002140
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002141 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002142 bool SwappedForXor = false;
2143 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002144 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002145 SwappedForXor = true;
2146 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002147
2148 // A | ( A ^ B) -> A | B
2149 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002150 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002151 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2152 if (Op0 == A || Op0 == B)
2153 return BinaryOperator::CreateOr(A, B);
2154
Chad Rosier7813dce2012-04-26 23:29:14 +00002155 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2156 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2157 return BinaryOperator::CreateOr(A, B);
2158
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002159 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2160 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2161 return BinaryOperator::CreateOr(Not, Op0);
2162 }
2163 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2164 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2165 return BinaryOperator::CreateOr(Not, Op0);
2166 }
2167 }
2168
2169 // A | ~(A | B) -> A | ~B
2170 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002171 if (match(Op1, m_Not(m_Value(A))))
2172 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002173 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2174 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2175 B->getOpcode() == Instruction::Xor)) {
2176 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2177 B->getOperand(0);
2178 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2179 return BinaryOperator::CreateOr(Not, Op0);
2180 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002181
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002182 // (A & B) | (~A ^ B) -> (~A ^ B)
2183 // (A & B) | (B ^ ~A) -> (~A ^ B)
2184 // (B & A) | (~A ^ B) -> (~A ^ B)
2185 // (B & A) | (B ^ ~A) -> (~A ^ B)
2186 // The match order is important: match the xor first because the 'not'
2187 // operation defines 'A'. We do not need to match the xor as Op0 because the
2188 // xor was canonicalized to Op1 above.
2189 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2190 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002191 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2192
Eli Friedmane06535b2012-03-16 00:52:42 +00002193 if (SwappedForXor)
2194 std::swap(Op0, Op1);
2195
David Majnemer3d6f80b2014-11-28 19:58:29 +00002196 {
2197 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2198 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2199 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002200 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002201 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002202
David Majnemer3d6f80b2014-11-28 19:58:29 +00002203 // TODO: Make this recursive; it's a little tricky because an arbitrary
2204 // number of 'or' instructions might have to be created.
2205 Value *X, *Y;
2206 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2207 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002208 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002209 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002210 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002211 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002212 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002213 }
2214 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2215 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002216 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002217 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002218 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002219 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002220 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002221 }
2222 }
2223
Chris Lattner4e8137d2010-02-11 06:26:33 +00002224 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2225 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2226 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002227 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002228 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002229
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002230 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2231 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002232
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002233 // 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 +00002234 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002235 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002236 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002237 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002238 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002239 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2240
Owen Andersonc237a842010-09-13 17:59:27 +00002241 // Note: If we've gotten to the point of visiting the outer OR, then the
2242 // inner one couldn't be simplified. If it was a constant, then it won't
2243 // be simplified by a later pass either, so we try swapping the inner/outer
2244 // ORs in the hopes that we'll be able to simplify it this way.
2245 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002246 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002247 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2248 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2249 Value *Inner = Builder->CreateOr(A, Op1);
2250 Inner->takeName(Op0);
2251 return BinaryOperator::CreateOr(Inner, C1);
2252 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002253
Bill Wendling23242092013-02-16 23:41:36 +00002254 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2255 // Since this OR statement hasn't been optimized further yet, we hope
2256 // that this transformation will allow the new ORs to be optimized.
2257 {
Craig Topperf40110f2014-04-25 05:29:35 +00002258 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002259 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2260 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2261 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2262 Value *orTrue = Builder->CreateOr(A, C);
2263 Value *orFalse = Builder->CreateOr(B, D);
2264 return SelectInst::Create(X, orTrue, orFalse);
2265 }
2266 }
2267
Craig Topperf40110f2014-04-25 05:29:35 +00002268 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002269}
2270
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002271/// A ^ B can be specified using other logic ops in a variety of patterns. We
2272/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002273static Instruction *foldXorToXor(BinaryOperator &I,
2274 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002275 assert(I.getOpcode() == Instruction::Xor);
2276 Value *Op0 = I.getOperand(0);
2277 Value *Op1 = I.getOperand(1);
2278 Value *A, *B;
2279
2280 // There are 4 commuted variants for each of the basic patterns.
2281
2282 // (A & B) ^ (A | B) -> A ^ B
2283 // (A & B) ^ (B | A) -> A ^ B
2284 // (A | B) ^ (A & B) -> A ^ B
2285 // (A | B) ^ (B & A) -> A ^ B
2286 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2287 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2288 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2289 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2290 I.setOperand(0, A);
2291 I.setOperand(1, B);
2292 return &I;
2293 }
2294
2295 // (A | ~B) ^ (~A | B) -> A ^ B
2296 // (~B | A) ^ (~A | B) -> A ^ B
2297 // (~A | B) ^ (A | ~B) -> A ^ B
2298 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002299 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2300 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2301 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2302 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002303 I.setOperand(0, A);
2304 I.setOperand(1, B);
2305 return &I;
2306 }
2307
2308 // (A & ~B) ^ (~A & B) -> A ^ B
2309 // (~B & A) ^ (~A & B) -> A ^ B
2310 // (~A & B) ^ (A & ~B) -> A ^ B
2311 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002312 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2313 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2314 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2315 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002316 I.setOperand(0, A);
2317 I.setOperand(1, B);
2318 return &I;
2319 }
2320
Craig Topperf60ab472017-07-02 01:15:51 +00002321 // For the remaining cases we need to get rid of one of the operands.
2322 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2323 return nullptr;
2324
2325 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2326 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2327 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2328 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2329 // Complexity sorting ensures the not will be on the right side.
2330 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2331 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2332 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2333 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2334 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2335
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002336 return nullptr;
2337}
2338
Sanjay Patel5e456b92017-05-18 20:53:16 +00002339Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2340 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2341 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2342 LHS->getOperand(1) == RHS->getOperand(0))
2343 LHS->swapOperands();
2344 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2345 LHS->getOperand(1) == RHS->getOperand(1)) {
2346 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2347 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2348 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2349 bool isSigned = LHS->isSigned() || RHS->isSigned();
2350 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2351 }
2352 }
2353
Sanjay Pateladca8252017-06-20 12:40:55 +00002354 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2355 // into those logic ops. That is, try to turn this into an and-of-icmps
2356 // because we have many folds for that pattern.
2357 //
2358 // This is based on a truth table definition of xor:
2359 // X ^ Y --> (X | Y) & !(X & Y)
2360 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2361 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2362 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2363 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2364 // TODO: Independently handle cases where the 'and' side is a constant.
2365 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2366 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2367 RHS->setPredicate(RHS->getInversePredicate());
2368 return Builder->CreateAnd(LHS, RHS);
2369 }
2370 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002371 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002372 LHS->setPredicate(LHS->getInversePredicate());
2373 return Builder->CreateAnd(LHS, RHS);
2374 }
2375 }
2376 }
2377
Sanjay Patel5e456b92017-05-18 20:53:16 +00002378 return nullptr;
2379}
2380
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002381// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2382// here. We should standardize that construct where it is needed or choose some
2383// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002384Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002385 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002386 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2387
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002388 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002389 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002390
Craig Toppera4205622017-06-09 03:21:29 +00002391 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002392 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002393
Craig Topperf60ab472017-07-02 01:15:51 +00002394 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002395 return NewXor;
2396
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002397 // (A&B)^(A&C) -> A&(B^C) etc
2398 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002400
Craig Topper9d4171a2012-12-20 07:09:41 +00002401 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002402 // purpose is to compute bits we don't care about.
2403 if (SimplifyDemandedInstructionBits(I))
2404 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002405
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002406 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002407 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002408
Sanjay Patel6381db12017-05-02 15:31:40 +00002409 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2410 Value *X, *Y;
2411
2412 // We must eliminate the and/or (one-use) for these transforms to not increase
2413 // the instruction count.
2414 // ~(~X & Y) --> (X | ~Y)
2415 // ~(Y & ~X) --> (X | ~Y)
2416 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2417 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2418 return BinaryOperator::CreateOr(X, NotY);
2419 }
2420 // ~(~X | Y) --> (X & ~Y)
2421 // ~(Y | ~X) --> (X & ~Y)
2422 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2423 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2424 return BinaryOperator::CreateAnd(X, NotY);
2425 }
2426
Sanjay Patel3b863f82017-04-22 18:05:35 +00002427 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002428 BinaryOperator *NotVal;
2429 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2430 if (NotVal->getOpcode() == Instruction::And ||
2431 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002432 // Apply DeMorgan's Law when inverts are free:
2433 // ~(X & Y) --> (~X | ~Y)
2434 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002435 if (IsFreeToInvert(NotVal->getOperand(0),
2436 NotVal->getOperand(0)->hasOneUse()) &&
2437 IsFreeToInvert(NotVal->getOperand(1),
2438 NotVal->getOperand(1)->hasOneUse())) {
2439 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2440 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2441 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002442 return BinaryOperator::CreateOr(NotX, NotY);
2443 return BinaryOperator::CreateAnd(NotX, NotY);
2444 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002445 }
2446
2447 // ~(~X >>s Y) --> (X >>s Y)
2448 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2449 return BinaryOperator::CreateAShr(X, Y);
2450
2451 // If we are inverting a right-shifted constant, we may be able to eliminate
2452 // the 'not' by inverting the constant and using the opposite shift type.
2453 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2454 // but we must check that in case that transform has not fired yet.
2455 const APInt *C;
2456 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2457 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2458 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2459 return BinaryOperator::CreateLShr(NotC, Y);
2460 }
2461
2462 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2463 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2464 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2465 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002466 }
2467 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002468
Craig Topper798a19a2017-06-29 00:07:08 +00002469 // not (cmp A, B) = !cmp A, B
Sanjay Patel33439f92017-04-12 15:11:33 +00002470 ICmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002471 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002472 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2473 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002474 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002475
Craig Topper9d1821b2017-04-09 06:12:31 +00002476 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002477 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2478 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2479 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2480 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2481 Instruction::CastOps Opcode = Op0C->getOpcode();
2482 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002483 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002484 Op0C->getDestTy()))) {
2485 CI->setPredicate(CI->getInversePredicate());
2486 return CastInst::Create(Opcode, CI, Op0C->getType());
2487 }
2488 }
2489 }
2490 }
2491
2492 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2493 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002494 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002495 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2496 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002497 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2498 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002499 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002500
Chris Lattner0a8191e2010-01-05 07:50:36 +00002501 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2502 if (Op0I->getOpcode() == Instruction::Add) {
2503 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002504 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002505 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002506 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2507 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002508 } else if (RHSC->getValue().isSignMask()) {
2509 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002510 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002511 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2512
2513 }
2514 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002515 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002516 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2517 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002518 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002519 // Anything in both C1 and C2 is known to be zero, remove it from
2520 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002521 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002522 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002523 ConstantExpr::getNot(CommonBits));
2524 Worklist.Add(Op0I);
2525 I.setOperand(0, Op0I->getOperand(0));
2526 I.setOperand(1, NewRHS);
2527 return &I;
2528 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002529 } else if (Op0I->getOpcode() == Instruction::LShr) {
2530 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2531 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002532 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002533 ConstantInt *C1;
2534 if (Op0I->hasOneUse() &&
2535 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2536 E1->getOpcode() == Instruction::Xor &&
2537 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2538 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002539 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002540 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2541 FoldConst ^= C3->getValue();
2542 // Prepare the two operands.
2543 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2544 Opnd0->takeName(Op0I);
2545 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2546 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2547
2548 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2549 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002550 }
2551 }
2552 }
Craig Topper86173602017-04-04 20:26:25 +00002553 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554
Craig Topper86173602017-04-04 20:26:25 +00002555 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002556 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2557 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002558
Craig Topper76394602017-04-10 06:53:23 +00002559 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002560 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002561 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002562 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002563 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002564 std::swap(A, B);
2565 }
2566 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002567 I.swapOperands(); // Simplified below.
2568 std::swap(Op0, Op1);
2569 }
Craig Topper76394602017-04-10 06:53:23 +00002570 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002571 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002572 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002573 std::swap(A, B);
2574 }
2575 if (B == Op0) { // A^(B&A) -> (B&A)^A
2576 I.swapOperands(); // Simplified below.
2577 std::swap(Op0, Op1);
2578 }
2579 }
2580 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002581
Craig Topper76394602017-04-10 06:53:23 +00002582 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002583 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002584 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002585 if (A == Op1) // (B|A)^B == (A|B)^B
2586 std::swap(A, B);
2587 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002588 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002589 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002590 if (A == Op1) // (A&B)^A -> (B&A)^A
2591 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002592 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002593 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002594 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002595 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002596 }
2597 }
2598 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002599
Craig Topper76394602017-04-10 06:53:23 +00002600 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002601 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002602 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002603 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2604 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002605 if (D == A)
2606 return BinaryOperator::CreateXor(
2607 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2608 if (D == B)
2609 return BinaryOperator::CreateXor(
2610 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002611 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002612 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002613 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2614 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002615 if (D == A)
2616 return BinaryOperator::CreateXor(
2617 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2618 if (D == B)
2619 return BinaryOperator::CreateXor(
2620 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002621 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002622 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002623 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002624 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002625 return BinaryOperator::CreateOr(A, B);
2626 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002627 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002628 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002629 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002630 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002631
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002632 // (A & ~B) ^ ~A -> ~(A & B)
2633 // (~B & A) ^ ~A -> ~(A & B)
2634 Value *A, *B;
2635 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002636 match(Op1, m_Not(m_Specific(A))))
2637 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2638
Sanjay Patel5e456b92017-05-18 20:53:16 +00002639 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2640 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2641 if (Value *V = foldXorOfICmps(LHS, RHS))
2642 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002643
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002644 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2645 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002646
Craig Topperf40110f2014-04-25 05:29:35 +00002647 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002648}