blob: a59b43d6af5feab7185f644dee250182fc6cae54 [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
Chris Lattner0a8191e2010-01-05 07:50:36 +000026static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000031 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 return Operand;
33 }
Craig Topper9d4171a2012-12-20 07:09:41 +000034
Chris Lattner0a8191e2010-01-05 07:50:36 +000035 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000039}
40
Sanjay Patel18549272015-09-08 18:24:36 +000041/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000042/// a four bit mask.
43static unsigned getFCmpCode(FCmpInst::Predicate CC) {
44 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
45 "Unexpected FCmp predicate!");
46 // Take advantage of the bit pattern of FCmpInst::Predicate here.
47 // U L G E
48 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
49 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
50 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
51 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
52 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
53 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
54 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
55 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
56 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
57 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
58 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
59 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
60 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
61 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
62 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
63 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
64 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000065}
66
Sanjay Patel18549272015-09-08 18:24:36 +000067/// This is the complement of getICmpCode, which turns an opcode and two
68/// operands into either a constant true or false, or a brand new ICmp
69/// instruction. The sign is passed in to determine which kind of predicate to
70/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000071static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000073 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75 return NewConstant;
76 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000077}
78
Sanjay Patel18549272015-09-08 18:24:36 +000079/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000080/// operands into either a FCmp instruction, or a true/false constant.
81static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Chris Lattner067459c2010-03-05 08:46:26 +000082 InstCombiner::BuilderTy *Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000083 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
84 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
85 "Unexpected FCmp predicate!");
86 if (Pred == FCmpInst::FCMP_FALSE)
87 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
88 if (Pred == FCmpInst::FCMP_TRUE)
89 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner067459c2010-03-05 08:46:26 +000090 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000091}
92
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000093/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
94/// \param I Binary operator to transform.
95/// \return Pointer to node that must replace the original binary operator, or
96/// null pointer if no transformation was made.
97Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
98 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
99
100 // Can't do vectors.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000101 if (I.getType()->isVectorTy())
102 return nullptr;
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000103
104 // Can only do bitwise ops.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000105 if (!I.isBitwiseLogicOp())
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000106 return nullptr;
107
108 Value *OldLHS = I.getOperand(0);
109 Value *OldRHS = I.getOperand(1);
110 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
111 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
112 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
113 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
114 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
115 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
116
117 if (!IsBswapLHS && !IsBswapRHS)
118 return nullptr;
119
120 if (!IsBswapLHS && !ConstLHS)
121 return nullptr;
122
123 if (!IsBswapRHS && !ConstRHS)
124 return nullptr;
125
126 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
127 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
128 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
129 Builder->getInt(ConstLHS->getValue().byteSwap());
130
131 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
132 Builder->getInt(ConstRHS->getValue().byteSwap());
133
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000134 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000135 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000136 return Builder->CreateCall(F, BinOp);
137}
138
Sanjay Patel18549272015-09-08 18:24:36 +0000139/// This handles expressions of the form ((val OP C1) & C2). Where
140/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
141/// guaranteed to be a binary operator.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142Instruction *InstCombiner::OptAndOp(Instruction *Op,
143 ConstantInt *OpRHS,
144 ConstantInt *AndRHS,
145 BinaryOperator &TheAnd) {
146 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000147 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000148 if (!Op->isShift())
149 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
150
151 switch (Op->getOpcode()) {
152 case Instruction::Xor:
153 if (Op->hasOneUse()) {
154 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
155 Value *And = Builder->CreateAnd(X, AndRHS);
156 And->takeName(Op);
157 return BinaryOperator::CreateXor(And, Together);
158 }
159 break;
160 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000161 if (Op->hasOneUse()){
162 if (Together != OpRHS) {
163 // (X | C1) & C2 --> (X | (C1&C2)) & C2
164 Value *Or = Builder->CreateOr(X, Together);
165 Or->takeName(Op);
166 return BinaryOperator::CreateAnd(Or, AndRHS);
167 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000168
Owen Andersonc237a842010-09-13 17:59:27 +0000169 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
170 if (TogetherCI && !TogetherCI->isZero()){
171 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
172 // NOTE: This reduces the number of bits set in the & mask, which
173 // can expose opportunities for store narrowing.
174 Together = ConstantExpr::getXor(AndRHS, Together);
175 Value *And = Builder->CreateAnd(X, Together);
176 And->takeName(Op);
177 return BinaryOperator::CreateOr(And, OpRHS);
178 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000179 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000180
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181 break;
182 case Instruction::Add:
183 if (Op->hasOneUse()) {
184 // Adding a one to a single bit bit-field should be turned into an XOR
185 // of the bit. First thing to check is to see if this AND is with a
186 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000187 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000188
189 // If there is only one bit set.
190 if (AndRHSV.isPowerOf2()) {
191 // Ok, at this point, we know that we are masking the result of the
192 // ADD down to exactly one bit. If the constant we are adding has
193 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000194 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000195
196 // Check to see if any bits below the one bit set in AndRHSV are set.
197 if ((AddRHS & (AndRHSV-1)) == 0) {
198 // If not, the only thing that can effect the output of the AND is
199 // the bit specified by AndRHSV. If that bit is set, the effect of
200 // the XOR is to toggle the bit. If it is clear, then the ADD has
201 // no effect.
202 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
203 TheAnd.setOperand(0, X);
204 return &TheAnd;
205 } else {
206 // Pull the XOR out of the AND.
207 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
208 NewAnd->takeName(Op);
209 return BinaryOperator::CreateXor(NewAnd, AndRHS);
210 }
211 }
212 }
213 }
214 break;
215
216 case Instruction::Shl: {
217 // We know that the AND will not produce any of the bits shifted in, so if
218 // the anded constant includes them, clear them now!
219 //
220 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
221 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
222 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000223 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000224
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000225 if (CI->getValue() == ShlMask)
226 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000227 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000228
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000229 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000230 TheAnd.setOperand(1, CI);
231 return &TheAnd;
232 }
233 break;
234 }
235 case Instruction::LShr: {
236 // We know that the AND will not produce any of the bits shifted in, so if
237 // the anded constant includes them, clear them now! This only applies to
238 // unsigned shifts, because a signed shr may bring in set bits!
239 //
240 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
241 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
242 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000243 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000244
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000245 if (CI->getValue() == ShrMask)
246 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000247 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000248
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000249 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000250 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
251 return &TheAnd;
252 }
253 break;
254 }
255 case Instruction::AShr:
256 // Signed shr.
257 // See if this is shifting in some sign extension, then masking it out
258 // with an and.
259 if (Op->hasOneUse()) {
260 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
261 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
262 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000263 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000264 if (C == AndRHS) { // Masking out bits shifted in.
265 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
266 // Make the argument unsigned.
267 Value *ShVal = Op->getOperand(0);
268 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
269 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
270 }
271 }
272 break;
273 }
Craig Topperf40110f2014-04-25 05:29:35 +0000274 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000275}
276
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000277/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000278/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
279/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000280Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000281 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000282 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000284
Sanjay Patel85d79742016-08-31 19:49:56 +0000285 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000286 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000287 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000288
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000289 // V >= Min && V < Hi --> V < Hi
290 // V < Min || V >= Hi --> V >= Hi
291 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000292 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000293 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000294 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000295 }
296
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000297 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
298 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000299 Value *VMinusLo =
300 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
301 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000302 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000303}
304
Sanjay Patel18549272015-09-08 18:24:36 +0000305/// Returns true iff Val consists of one contiguous run of 1s with any number
306/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
307/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
308/// not, since all 1s are not contiguous.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000309static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
310 const APInt& V = Val->getValue();
311 uint32_t BitWidth = Val->getType()->getBitWidth();
312 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
313
314 // look for the first zero bit after the run of ones
315 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
316 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000317 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000318 return true;
319}
320
Sanjay Patel18549272015-09-08 18:24:36 +0000321/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
322/// whether the operator is a sub. If we can fold one of the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000323///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000324/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
325/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
326/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327///
328/// return (A +/- B).
329///
330Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
331 ConstantInt *Mask, bool isSub,
332 Instruction &I) {
333 Instruction *LHSI = dyn_cast<Instruction>(LHS);
334 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000335 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000336
337 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
338
339 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000340 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000341 case Instruction::And:
342 if (ConstantExpr::getAnd(N, Mask) == Mask) {
343 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000344 if ((Mask->getValue().countLeadingZeros() +
345 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000346 Mask->getValue().getBitWidth())
347 break;
348
349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
350 // part, we don't need any explicit masks to take them out of A. If that
351 // is all N is, ignore it.
352 uint32_t MB = 0, ME = 0;
353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
354 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
355 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000356 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000357 break;
358 }
359 }
Craig Topperf40110f2014-04-25 05:29:35 +0000360 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000361 case Instruction::Or:
362 case Instruction::Xor:
363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000364 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000365 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
366 && ConstantExpr::getAnd(N, Mask)->isNullValue())
367 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000368 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000369 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000370
Chris Lattner0a8191e2010-01-05 07:50:36 +0000371 if (isSub)
372 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
373 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
374}
375
Owen Anderson3fe002d2010-09-08 22:16:17 +0000376/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000377/// One of A and B is considered the mask, the other the value. This is
378/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000379/// contains only "Mask", then both A and B can be considered masks.
380/// If A is the mask, then it was proven, that (A & C) == C. This
381/// is trivial if C == A, or C == 0. If both A and C are constants, this
382/// proof is also easy.
383/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000384/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000385/// if (A & B) == A, or all bits of A are set in B.
386/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000387/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000388/// if (A & B) == 0, or all bits of A are cleared in B.
389/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000390/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000391/// contain any number of one bits and zero bits.
392/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
393/// The Part "Not" means, that in above descriptions "==" should be replaced
394/// by "!=".
395/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
396/// If the mask A contains a single bit, then the following is equivalent:
397/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
398/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
399enum MaskedICmpType {
400 FoldMskICmp_AMask_AllOnes = 1,
401 FoldMskICmp_AMask_NotAllOnes = 2,
402 FoldMskICmp_BMask_AllOnes = 4,
403 FoldMskICmp_BMask_NotAllOnes = 8,
404 FoldMskICmp_Mask_AllZeroes = 16,
405 FoldMskICmp_Mask_NotAllZeroes = 32,
406 FoldMskICmp_AMask_Mixed = 64,
407 FoldMskICmp_AMask_NotMixed = 128,
408 FoldMskICmp_BMask_Mixed = 256,
409 FoldMskICmp_BMask_NotMixed = 512
410};
411
Sanjay Patel18549272015-09-08 18:24:36 +0000412/// Return the set of pattern classes (from MaskedICmpType)
413/// that (icmp SCC (A & B), C) satisfies.
Craig Topper9d4171a2012-12-20 07:09:41 +0000414static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415 ICmpInst::Predicate SCC)
416{
417 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
418 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
419 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
420 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000421 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000422 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000423 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 BCst->getValue().isPowerOf2());
425 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000426 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000427 // if C is zero, then both A and B qualify as mask
428 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429 FoldMskICmp_AMask_Mixed |
430 FoldMskICmp_BMask_Mixed)
431 : (FoldMskICmp_Mask_NotAllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000432 FoldMskICmp_AMask_NotMixed |
433 FoldMskICmp_BMask_NotMixed));
434 if (icmp_abit)
435 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000436 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000437 : (FoldMskICmp_AMask_AllOnes |
438 FoldMskICmp_AMask_Mixed));
439 if (icmp_bbit)
440 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000441 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000442 : (FoldMskICmp_BMask_AllOnes |
443 FoldMskICmp_BMask_Mixed));
444 return result;
445 }
446 if (A == C) {
447 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
448 FoldMskICmp_AMask_Mixed)
449 : (FoldMskICmp_AMask_NotAllOnes |
450 FoldMskICmp_AMask_NotMixed));
451 if (icmp_abit)
452 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
453 FoldMskICmp_AMask_NotMixed)
454 : (FoldMskICmp_Mask_AllZeroes |
455 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000456 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000457 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000458 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
459 : FoldMskICmp_AMask_NotMixed);
460 }
Craig Topperae48cb22012-12-20 07:15:54 +0000461 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000462 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
463 FoldMskICmp_BMask_Mixed)
464 : (FoldMskICmp_BMask_NotAllOnes |
465 FoldMskICmp_BMask_NotMixed));
466 if (icmp_bbit)
467 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000468 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000469 : (FoldMskICmp_Mask_AllZeroes |
470 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000471 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000472 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000473 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
474 : FoldMskICmp_BMask_NotMixed);
475 }
476 return result;
477}
478
Tim Northoverc0756c42013-09-04 11:57:13 +0000479/// Convert an analysis of a masked ICmp into its equivalent if all boolean
480/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
481/// is adjacent to the corresponding normal flag (recording ==), this just
482/// involves swapping those bits over.
483static unsigned conjugateICmpMask(unsigned Mask) {
484 unsigned NewMask;
485 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
486 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
487 FoldMskICmp_BMask_Mixed))
488 << 1;
489
490 NewMask |=
491 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
492 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
493 FoldMskICmp_BMask_NotMixed))
494 >> 1;
495
496 return NewMask;
497}
498
Sanjay Patel18549272015-09-08 18:24:36 +0000499/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
500/// Return the set of pattern classes (from MaskedICmpType)
501/// that both LHS and RHS satisfy.
Craig Topper9d4171a2012-12-20 07:09:41 +0000502static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000503 Value*& B, Value*& C,
504 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000505 ICmpInst *LHS, ICmpInst *RHS,
506 ICmpInst::Predicate &LHSCC,
507 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000508 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
509 // vectors are not (yet?) supported
510 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
511
512 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000513 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000514 // and L11 & L12 == L21 & L22. The same goes for RHS.
515 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000516 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000517 // above.
518 Value *L1 = LHS->getOperand(0);
519 Value *L2 = LHS->getOperand(1);
520 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000521 // Check whether the icmp can be decomposed into a bit test.
522 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000523 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000524 } else {
525 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000526 if (!L1->getType()->isIntegerTy()) {
527 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000528 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000529 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
530 // Any icmp can be viewed as being trivially masked; if it allows us to
531 // remove one, it's worth it.
532 L11 = L1;
533 L12 = Constant::getAllOnesValue(L1->getType());
534 }
535
536 if (!L2->getType()->isIntegerTy()) {
537 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000538 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000539 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
540 L21 = L2;
541 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000542 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000543 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000544
545 // Bail if LHS was a icmp that can't be decomposed into an equality.
546 if (!ICmpInst::isEquality(LHSCC))
547 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000548
549 Value *R1 = RHS->getOperand(0);
550 Value *R2 = RHS->getOperand(1);
551 Value *R11,*R12;
552 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000553 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
554 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
555 A = R11; D = R12;
556 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
557 A = R12; D = R11;
558 } else {
559 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 }
Craig Topperf40110f2014-04-25 05:29:35 +0000561 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000562 } else if (R1->getType()->isIntegerTy()) {
563 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
564 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000565 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000566 R11 = R1;
567 R12 = Constant::getAllOnesValue(R1->getType());
568 }
569
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000570 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
571 A = R11; D = R12; E = R2; ok = true;
572 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000573 A = R12; D = R11; E = R2; ok = true;
574 }
575 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000576
577 // Bail if RHS was a icmp that can't be decomposed into an equality.
578 if (!ICmpInst::isEquality(RHSCC))
579 return 0;
580
Chad Rosier58919cc2016-05-09 21:37:43 +0000581 // Look for ANDs on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000582 if (!ok && R2->getType()->isIntegerTy()) {
583 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
584 R11 = R2;
585 R12 = Constant::getAllOnesValue(R2->getType());
586 }
587
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000588 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
589 A = R11; D = R12; E = R1; ok = true;
590 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000591 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000592 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000593 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000594 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000595 }
596 if (!ok)
597 return 0;
598
599 if (L11 == A) {
600 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000601 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000602 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000603 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000604 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000605 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000606 B = L21; C = L1;
607 }
608
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000609 unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
610 unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
611 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000612}
Sanjay Patel18549272015-09-08 18:24:36 +0000613
614/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
615/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000616static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
617 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000618 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000619 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000620 unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000621 LHSCC, RHSCC);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000622 if (Mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000623 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
624 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000625
Tim Northoverc0756c42013-09-04 11:57:13 +0000626 // In full generality:
627 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
628 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
629 //
630 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
631 // equivalent to (icmp (A & X) !Op Y).
632 //
633 // Therefore, we can pretend for the rest of this function that we're dealing
634 // with the conjunction, provided we flip the sense of any comparisons (both
635 // input and output).
636
637 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000638 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000639 if (!IsAnd) {
640 // Convert the masking analysis into its equivalent with negated
641 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000642 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000643 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000644
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000645 if (Mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000646 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000647 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000648 Value *NewOr = Builder->CreateOr(B, D);
649 Value *NewAnd = Builder->CreateAnd(A, NewOr);
650 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000651 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000652 // with B and D, having a single bit set.
653 Value *Zero = Constant::getNullValue(A->getType());
654 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000655 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000656 if (Mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000657 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000658 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000659 Value *NewOr = Builder->CreateOr(B, D);
660 Value *NewAnd = Builder->CreateAnd(A, NewOr);
661 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000662 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000663 if (Mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000664 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000665 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000666 Value *NewAnd1 = Builder->CreateAnd(B, D);
667 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
668 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000669 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000670
671 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000672 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000673 // easy cases for now" decision.
674 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000675 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000676 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000677 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000678
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000679 if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000680 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
681 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
682 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
683 // Only valid if one of the masks is a superset of the other (check "B&D" is
684 // the same as either B or D).
685 APInt NewMask = BCst->getValue() & DCst->getValue();
686
687 if (NewMask == BCst->getValue())
688 return LHS;
689 else if (NewMask == DCst->getValue())
690 return RHS;
691 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000692 if (Mask & FoldMskICmp_AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000693 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
694 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
695 // Only valid if one of the masks is a superset of the other (check "B|D" is
696 // the same as either B or D).
697 APInt NewMask = BCst->getValue() | DCst->getValue();
698
699 if (NewMask == BCst->getValue())
700 return LHS;
701 else if (NewMask == DCst->getValue())
702 return RHS;
703 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000704 if (Mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000705 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000706 // We already know that B & C == C && D & E == E.
707 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
708 // C and E, which are shared by both the mask B and the mask D, don't
709 // contradict, then we can transform to
710 // -> (icmp eq (A & (B|D)), (C|E))
711 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000712 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000713 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000714 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000715 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000716 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000717 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000718 if (!ECst) return nullptr;
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000719 if (LHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000720 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000721 if (RHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000722 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000723 // If there is a conflict, we should actually return a false for the
724 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000725 if (((BCst->getValue() & DCst->getValue()) &
726 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000727 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000728 Value *NewOr1 = Builder->CreateOr(B, D);
729 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
730 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
731 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000732 }
Craig Topperf40110f2014-04-25 05:29:35 +0000733 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000734}
735
Erik Ecksteind1817522014-12-03 10:39:15 +0000736/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
737/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
738/// If \p Inverted is true then the check is for the inverted range, e.g.
739/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
740Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
741 bool Inverted) {
742 // Check the lower range comparison, e.g. x >= 0
743 // InstCombine already ensured that if there is a constant it's on the RHS.
744 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
745 if (!RangeStart)
746 return nullptr;
747
748 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
749 Cmp0->getPredicate());
750
751 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
752 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
753 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
754 return nullptr;
755
756 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
757 Cmp1->getPredicate());
758
759 Value *Input = Cmp0->getOperand(0);
760 Value *RangeEnd;
761 if (Cmp1->getOperand(0) == Input) {
762 // For the upper range compare we have: icmp x, n
763 RangeEnd = Cmp1->getOperand(1);
764 } else if (Cmp1->getOperand(1) == Input) {
765 // For the upper range compare we have: icmp n, x
766 RangeEnd = Cmp1->getOperand(0);
767 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
768 } else {
769 return nullptr;
770 }
771
772 // Check the upper range comparison, e.g. x < n
773 ICmpInst::Predicate NewPred;
774 switch (Pred1) {
775 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
776 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
777 default: return nullptr;
778 }
779
780 // This simplification is only valid if the upper range is not negative.
781 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000782 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000783 if (!IsNotNegative)
784 return nullptr;
785
786 if (Inverted)
787 NewPred = ICmpInst::getInversePredicate(NewPred);
788
789 return Builder->CreateICmp(NewPred, Input, RangeEnd);
790}
791
Sanjay Patel18549272015-09-08 18:24:36 +0000792/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000793Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000794 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
795
796 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
797 if (PredicatesFoldable(LHSCC, RHSCC)) {
798 if (LHS->getOperand(0) == RHS->getOperand(1) &&
799 LHS->getOperand(1) == RHS->getOperand(0))
800 LHS->swapOperands();
801 if (LHS->getOperand(0) == RHS->getOperand(0) &&
802 LHS->getOperand(1) == RHS->getOperand(1)) {
803 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
804 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
805 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000806 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000807 }
808 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000809
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000810 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000811 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000812 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000813
Erik Ecksteind1817522014-12-03 10:39:15 +0000814 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
815 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
816 return V;
817
818 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
819 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
820 return V;
821
Chris Lattner0a8191e2010-01-05 07:50:36 +0000822 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
823 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
824 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
825 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000826 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000827
Chris Lattner0a8191e2010-01-05 07:50:36 +0000828 if (LHSCst == RHSCst && LHSCC == RHSCC) {
829 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000830 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000832 if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
833 (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000834 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000835 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 }
837 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000838
Benjamin Kramer101720f2011-04-28 20:09:57 +0000839 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000840 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000841 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000842 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000843 LHS->hasOneUse() && RHS->hasOneUse()) {
844 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000845 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000846
847 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000848 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000849 if (match(Val2, m_Trunc(m_Value(V))) &&
850 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
851 SmallCst = RHSCst;
852 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000853 } else if (match(Val, m_Trunc(m_Value(V))) &&
854 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000855 SmallCst = LHSCst;
856 BigCst = RHSCst;
857 }
858
859 if (SmallCst && BigCst) {
860 unsigned BigBitSize = BigCst->getType()->getBitWidth();
861 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
862
863 // Check that the low bits are zero.
864 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000865 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000866 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
867 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
868 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
869 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
870 }
871 }
872 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000873
Chris Lattner0a8191e2010-01-05 07:50:36 +0000874 // From here on, we only handle:
875 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000876 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000877
Chris Lattner0a8191e2010-01-05 07:50:36 +0000878 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
879 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
880 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
881 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
882 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000883 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000884
Chris Lattner0a8191e2010-01-05 07:50:36 +0000885 // We can't fold (ugt x, C) & (sgt x, C2).
886 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000887 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000888
Chris Lattner0a8191e2010-01-05 07:50:36 +0000889 // Ensure that the larger constant is on the RHS.
890 bool ShouldSwap;
891 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000892 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000893 CmpInst::isSigned(RHSCC)))
894 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
895 else
896 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000897
Chris Lattner0a8191e2010-01-05 07:50:36 +0000898 if (ShouldSwap) {
899 std::swap(LHS, RHS);
900 std::swap(LHSCst, RHSCst);
901 std::swap(LHSCC, RHSCC);
902 }
903
Dan Gohman4a618822010-02-10 16:03:48 +0000904 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000905 // comparing a value against two constants and and'ing the result
906 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000907 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
908 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000909 // are not equal and that the larger constant is on the RHS
910 assert(LHSCst != RHSCst && "Compares not folded above?");
911
912 switch (LHSCC) {
913 default: llvm_unreachable("Unknown integer condition code!");
914 case ICmpInst::ICMP_EQ:
915 switch (RHSCC) {
916 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
918 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
919 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000920 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000921 }
922 case ICmpInst::ICMP_NE:
923 switch (RHSCC) {
924 default: llvm_unreachable("Unknown integer condition code!");
925 case ICmpInst::ICMP_ULT:
926 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000927 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +0000928 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patel85d79742016-08-31 19:49:56 +0000929 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
930 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000931 break; // (X != 13 & X u< 15) -> no change
932 case ICmpInst::ICMP_SLT:
933 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000934 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 break; // (X != 13 & X s< 15) -> no change
936 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
937 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
938 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000939 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000941 // Special case to get the ordering right when the values wrap around
942 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +0000943 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000944 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
946 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
947 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000948 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
949 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000950 }
951 break; // (X != 13 & X != 15) -> no change
952 }
953 break;
954 case ICmpInst::ICMP_ULT:
955 switch (RHSCC) {
956 default: llvm_unreachable("Unknown integer condition code!");
957 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
958 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000959 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
961 break;
962 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
963 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000964 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000965 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
966 break;
967 }
968 break;
969 case ICmpInst::ICMP_SLT:
970 switch (RHSCC) {
971 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
973 break;
974 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
975 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000976 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
978 break;
979 }
980 break;
981 case ICmpInst::ICMP_UGT:
982 switch (RHSCC) {
983 default: llvm_unreachable("Unknown integer condition code!");
984 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
985 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000986 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
988 break;
989 case ICmpInst::ICMP_NE:
990 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000991 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 break; // (X u> 13 & X != 15) -> no change
993 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patel85d79742016-08-31 19:49:56 +0000994 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
995 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000996 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
997 break;
998 }
999 break;
1000 case ICmpInst::ICMP_SGT:
1001 switch (RHSCC) {
1002 default: llvm_unreachable("Unknown integer condition code!");
1003 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1004 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001005 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001006 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1007 break;
1008 case ICmpInst::ICMP_NE:
1009 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001010 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001011 break; // (X s> 13 & X != 15) -> no change
1012 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patel85d79742016-08-31 19:49:56 +00001013 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
1014 true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001015 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1016 break;
1017 }
1018 break;
1019 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001020
Craig Topperf40110f2014-04-25 05:29:35 +00001021 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022}
1023
Sanjay Patel18549272015-09-08 18:24:36 +00001024/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1025/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001026Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001027 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1028 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1029 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1030
1031 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1032 // Swap RHS operands to match LHS.
1033 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1034 std::swap(Op1LHS, Op1RHS);
1035 }
1036
1037 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1038 // Suppose the relation between x and y is R, where R is one of
1039 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1040 // testing the desired relations.
1041 //
1042 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1043 // bool(R & CC0) && bool(R & CC1)
1044 // = bool((R & CC0) & (R & CC1))
1045 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1046 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1047 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1048 Builder);
1049
Chris Lattner0a8191e2010-01-05 07:50:36 +00001050 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1051 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001052 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001053 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001054
Chris Lattner0a8191e2010-01-05 07:50:36 +00001055 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1056 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1057 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1058 // If either of the constants are nans, then the whole thing returns
1059 // false.
1060 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001061 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001062 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001063 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001064
Chris Lattner0a8191e2010-01-05 07:50:36 +00001065 // Handle vector zeros. This occurs because the canonical form of
1066 // "fcmp ord x,x" is "fcmp ord x, 0".
1067 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1068 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001069 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001071 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001072
Craig Topperf40110f2014-04-25 05:29:35 +00001073 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001074}
1075
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001076/// Match De Morgan's Laws:
1077/// (~A & ~B) == (~(A | B))
1078/// (~A | ~B) == (~(A & B))
1079static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1080 InstCombiner::BuilderTy *Builder) {
1081 auto Opcode = I.getOpcode();
1082 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1083 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001084 // Flip the logic operation.
1085 if (Opcode == Instruction::And)
1086 Opcode = Instruction::Or;
1087 else
1088 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001089
1090 Value *Op0 = I.getOperand(0);
1091 Value *Op1 = I.getOperand(1);
1092 // TODO: Use pattern matchers instead of dyn_cast.
1093 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1094 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1095 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001096 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1097 I.getName() + ".demorgan");
1098 return BinaryOperator::CreateNot(LogicOp);
1099 }
1100
1101 return nullptr;
1102}
1103
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001104bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1105 Value *CastSrc = CI->getOperand(0);
1106
1107 // Noop casts and casts of constants should be eliminated trivially.
1108 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1109 return false;
1110
1111 // If this cast is paired with another cast that can be eliminated, we prefer
1112 // to have it eliminated.
1113 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1114 if (isEliminableCastPair(PrecedingCI, CI))
1115 return false;
1116
1117 // If this is a vector sext from a compare, then we don't want to break the
1118 // idiom where each element of the extended vector is either zero or all ones.
1119 if (CI->getOpcode() == Instruction::SExt &&
1120 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1121 return false;
1122
1123 return true;
1124}
1125
Sanjay Patel60312bc42016-09-12 00:16:23 +00001126/// Fold {and,or,xor} (cast X), C.
1127static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1128 InstCombiner::BuilderTy *Builder) {
1129 Constant *C;
1130 if (!match(Logic.getOperand(1), m_Constant(C)))
1131 return nullptr;
1132
1133 auto LogicOpc = Logic.getOpcode();
1134 Type *DestTy = Logic.getType();
1135 Type *SrcTy = Cast->getSrcTy();
1136
1137 // If the first operand is bitcast, move the logic operation ahead of the
1138 // bitcast (do the logic operation in the original type). This can eliminate
1139 // bitcasts and allow combines that would otherwise be impeded by the bitcast.
1140 Value *X;
1141 if (match(Cast, m_BitCast(m_Value(X)))) {
1142 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1143 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, NewConstant);
1144 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1145 }
1146
1147 // Similarly, move the logic operation ahead of a zext if the constant is
1148 // unchanged in the smaller source type. Performing the logic in a smaller
1149 // type may provide more information to later folds, and the smaller logic
1150 // instruction may be cheaper (particularly in the case of vectors).
1151 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1152 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1153 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1154 if (ZextTruncC == C) {
1155 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1156 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1157 return new ZExtInst(NewOp, DestTy);
1158 }
1159 }
1160
1161 return nullptr;
1162}
1163
1164/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001165Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001166 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001167 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001168
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001169 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001170 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001171 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001172 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001173
Sanjay Patel9bba7502016-03-03 19:19:04 +00001174 // This must be a cast from an integer or integer vector source type to allow
1175 // transformation of the logic operation to the source type.
1176 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001177 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001178 if (!SrcTy->isIntOrIntVectorTy())
1179 return nullptr;
1180
Sanjay Patel60312bc42016-09-12 00:16:23 +00001181 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1182 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001183
Sanjay Patel9bba7502016-03-03 19:19:04 +00001184 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1185 if (!Cast1)
1186 return nullptr;
1187
1188 // Both operands of the logic operation are casts. The casts must be of the
1189 // same type for reduction.
1190 auto CastOpcode = Cast0->getOpcode();
1191 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001192 return nullptr;
1193
1194 Value *Cast0Src = Cast0->getOperand(0);
1195 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001196
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001197 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001198 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001199 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1200 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001201 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001202 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001203
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001204 // For now, only 'and'/'or' have optimizations after this.
1205 if (LogicOpc == Instruction::Xor)
1206 return nullptr;
1207
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001208 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001209 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001210 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1211 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1212 if (ICmp0 && ICmp1) {
1213 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1214 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1215 if (Res)
1216 return CastInst::Create(CastOpcode, Res, DestTy);
1217 return nullptr;
1218 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001219
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001220 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001221 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001222 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1223 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1224 if (FCmp0 && FCmp1) {
1225 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1226 : FoldOrOfFCmps(FCmp0, FCmp1);
1227 if (Res)
1228 return CastInst::Create(CastOpcode, Res, DestTy);
1229 return nullptr;
1230 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001231
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001232 return nullptr;
1233}
1234
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001235static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1236 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1237
1238 // Canonicalize SExt or Not to the LHS
1239 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1240 std::swap(Op0, Op1);
1241 }
1242
1243 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1244 Value *X = nullptr;
1245 if (match(Op0, m_SExt(m_Value(X))) &&
1246 X->getType()->getScalarType()->isIntegerTy(1)) {
1247 Value *Zero = Constant::getNullValue(Op1->getType());
1248 return SelectInst::Create(X, Op1, Zero);
1249 }
1250
1251 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1252 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1253 X->getType()->getScalarType()->isIntegerTy(1)) {
1254 Value *Zero = Constant::getNullValue(Op0->getType());
1255 return SelectInst::Create(X, Zero, Op1);
1256 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001257
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001258 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
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001271 if (Value *V = SimplifyAndInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001272 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001274 // (A|B)&(A|C) -> A|(B&C) etc
1275 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001276 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001277
Craig Topper9d4171a2012-12-20 07:09:41 +00001278 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279 // purpose is to compute bits we don't care about.
1280 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001281 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001282
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001283 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001284 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001285
Chris Lattner0a8191e2010-01-05 07:50:36 +00001286 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1287 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288
1289 // Optimize a variety of ((val OP C1) & C2) combinations...
1290 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1291 Value *Op0LHS = Op0I->getOperand(0);
1292 Value *Op0RHS = Op0I->getOperand(1);
1293 switch (Op0I->getOpcode()) {
1294 default: break;
1295 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001296 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001297 // If the mask is only needed on one incoming arm, push it up.
1298 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001299
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001300 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001301 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001302 // Not masking anything out for the LHS, move to RHS.
1303 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1304 Op0RHS->getName()+".masked");
1305 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1306 }
1307 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001308 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001309 // Not masking anything out for the RHS, move to LHS.
1310 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1311 Op0LHS->getName()+".masked");
1312 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1313 }
1314
1315 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001316 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001317 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001318 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1319 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1320 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001321 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1322 return BinaryOperator::CreateAnd(V, AndRHS);
1323 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1324 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1325 break;
1326
1327 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001328 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1329 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1330 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001331 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1332 return BinaryOperator::CreateAnd(V, AndRHS);
1333
Balaram Makamccf59732015-08-20 15:35:00 +00001334 // -x & 1 -> x & 1
1335 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1336 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1337
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001338 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001339 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001340 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001341 uint32_t BitWidth = AndRHSMask.getBitWidth();
1342 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1343 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1344
Hal Finkel60db0582014-09-07 18:57:58 +00001345 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1347 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1348 }
1349 }
1350 break;
1351
1352 case Instruction::Shl:
1353 case Instruction::LShr:
1354 // (1 << x) & 1 --> zext(x == 0)
1355 // (1 >> x) & 1 --> zext(x == 0)
1356 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1357 Value *NewICmp =
1358 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1359 return new ZExtInst(NewICmp, I.getType());
1360 }
1361 break;
1362 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001363
Chris Lattner0a8191e2010-01-05 07:50:36 +00001364 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1365 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1366 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001367 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001368
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001369 // If this is an integer truncation, and if the source is an 'and' with
1370 // immediate, transform it. This frequently occurs for bitfield accesses.
1371 {
Craig Topperf40110f2014-04-25 05:29:35 +00001372 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001373 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1374 // Change: and (trunc (and X, YC) to T), C2
1375 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001376 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001377 // other simplifications.
1378 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1379 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1380 C3 = ConstantExpr::getAnd(C3, AndRHS);
1381 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001382 }
1383 }
1384
1385 // Try to fold constant and into select arguments.
1386 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1387 if (Instruction *R = FoldOpIntoSelect(I, SI))
1388 return R;
1389 if (isa<PHINode>(Op0))
1390 if (Instruction *NV = FoldOpIntoPhi(I))
1391 return NV;
1392 }
1393
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001394 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1395 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001396
Chris Lattner0a8191e2010-01-05 07:50:36 +00001397 {
Craig Topperf40110f2014-04-25 05:29:35 +00001398 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001399 // (A|B) & ~(A&B) -> A^B
1400 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1401 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1402 ((A == C && B == D) || (A == D && B == C)))
1403 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001404
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405 // ~(A&B) & (A|B) -> A^B
1406 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1407 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1408 ((A == C && B == D) || (A == D && B == C)))
1409 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001410
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001411 // A&(A^B) => A & ~B
1412 {
1413 Value *tmpOp0 = Op0;
1414 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001415 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001416 if (A == Op1 || B == Op1 ) {
1417 tmpOp1 = Op0;
1418 tmpOp0 = Op1;
1419 // Simplify below
1420 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001421 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001422
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001423 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001424 if (B == tmpOp0) {
1425 std::swap(A, B);
1426 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001427 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001428 // A is originally -1 (or a vector of -1 and undefs), then we enter
1429 // an endless loop. By checking that A is non-constant we ensure that
1430 // we will never get to the loop.
1431 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001432 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001433 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001434 }
1435
1436 // (A&((~A)|B)) -> A&B
1437 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1438 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1439 return BinaryOperator::CreateAnd(A, Op1);
1440 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1441 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1442 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001443
1444 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1445 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1446 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1447 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1448 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1449
1450 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1451 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1452 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1453 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1454 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001455
1456 // (A | B) & ((~A) ^ B) -> (A & B)
1457 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1458 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1459 return BinaryOperator::CreateAnd(A, B);
1460
1461 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001462 // ((~A) ^ B) & (B | A) -> (A & B)
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001463 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001464 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001465 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001466 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001467
David Majnemer5e96f1b2014-08-30 06:18:20 +00001468 {
1469 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1470 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1471 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001472 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001473 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001474
David Majnemer5e96f1b2014-08-30 06:18:20 +00001475 // TODO: Make this recursive; it's a little tricky because an arbitrary
1476 // number of 'and' instructions might have to be created.
1477 Value *X, *Y;
1478 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1479 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1480 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001481 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001482 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1483 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001484 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001485 }
1486 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1487 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1488 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001489 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001490 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1491 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001492 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001493 }
1494 }
1495
Chris Lattner4e8137d2010-02-11 06:26:33 +00001496 // If and'ing two fcmp, try combine them into one.
1497 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1498 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001499 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001500 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001501
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001502 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1503 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001504
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001505 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1506 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001507
Craig Topperf40110f2014-04-25 05:29:35 +00001508 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001509}
1510
Chad Rosiera00df492016-05-25 16:22:14 +00001511/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1512/// insert the new intrinsic and return it.
1513Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1515
1516 // Look through zero extends.
1517 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1518 Op0 = Ext->getOperand(0);
1519
1520 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1521 Op1 = Ext->getOperand(0);
1522
1523 // (A | B) | C and A | (B | C) -> bswap if possible.
1524 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1525 match(Op1, m_Or(m_Value(), m_Value()));
1526
1527 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1528 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1529 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1530
1531 // (A & B) | (C & D) -> bswap if possible.
1532 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1533 match(Op1, m_And(m_Value(), m_Value()));
1534
1535 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1536 return nullptr;
1537
James Molloyf01488e2016-01-15 09:20:19 +00001538 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001539 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001540 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001541 Instruction *LastInst = Insts.pop_back_val();
1542 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001543
James Molloyf01488e2016-01-15 09:20:19 +00001544 for (auto *Inst : Insts)
1545 Worklist.Add(Inst);
1546 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001547}
1548
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001549/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1550static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1551 unsigned NumElts = C1->getType()->getVectorNumElements();
1552 for (unsigned i = 0; i != NumElts; ++i) {
1553 Constant *EltC1 = C1->getAggregateElement(i);
1554 Constant *EltC2 = C2->getAggregateElement(i);
1555 if (!EltC1 || !EltC2)
1556 return false;
1557
1558 // One element must be all ones, and the other must be all zeros.
1559 // FIXME: Allow undef elements.
1560 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1561 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1562 return false;
1563 }
1564 return true;
1565}
1566
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001567/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1568/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1569/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001570static Value *getSelectCondition(Value *A, Value *B,
1571 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001572 // If these are scalars or vectors of i1, A can be used directly.
1573 Type *Ty = A->getType();
1574 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1575 return A;
1576
1577 // If A and B are sign-extended, look through the sexts to find the booleans.
1578 Value *Cond;
1579 if (match(A, m_SExt(m_Value(Cond))) &&
1580 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1581 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1582 m_SExt(m_Not(m_Specific(Cond))))))
1583 return Cond;
1584
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001585 // All scalar (and most vector) possibilities should be handled now.
1586 // Try more matches that only apply to non-splat constant vectors.
1587 if (!Ty->isVectorTy())
1588 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001589
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001590 // If both operands are constants, see if the constants are inverse bitmasks.
1591 Constant *AC, *BC;
1592 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1593 areInverseVectorBitmasks(AC, BC))
1594 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1595
1596 // If both operands are xor'd with constants using the same sexted boolean
1597 // operand, see if the constants are inverse bitmasks.
1598 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1599 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1600 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1601 areInverseVectorBitmasks(AC, BC)) {
1602 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1603 return Builder.CreateXor(Cond, AC);
1604 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001605 return nullptr;
1606}
1607
1608/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1609/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001610static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001611 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001612 // The potential condition of the select may be bitcasted. In that case, look
1613 // through its bitcast and the corresponding bitcast of the 'not' condition.
1614 Type *OrigType = A->getType();
1615 Value *SrcA, *SrcB;
Sanjay Patel664514f2016-07-08 21:17:51 +00001616 if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1617 match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001618 A = SrcA;
1619 B = SrcB;
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001620 }
1621
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001622 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001623 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001624 // The bitcasts will either all exist or all not exist. The builder will
1625 // not create unnecessary casts if the types already match.
1626 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1627 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1628 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1629 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001630 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001631
Craig Topperf40110f2014-04-25 05:29:35 +00001632 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001633}
1634
Sanjay Patel18549272015-09-08 18:24:36 +00001635/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001636Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1637 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001638 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1639
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001640 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1641 // if K1 and K2 are a one-bit mask.
1642 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1643 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1644
1645 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1646 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1647
1648 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1649 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1650 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1651 LAnd->getOpcode() == Instruction::And &&
1652 RAnd->getOpcode() == Instruction::And) {
1653
Craig Topperf40110f2014-04-25 05:29:35 +00001654 Value *Mask = nullptr;
1655 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001656 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001657 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001658 &DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001659 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001660 &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001661 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1662 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1663 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001664 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, &AC,
1665 CxtI, &DT) &&
1666 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, &AC,
1667 CxtI, &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001668 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1669 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1670 }
1671
1672 if (Masked)
1673 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1674 }
1675 }
1676
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001677 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1678 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1679 // The original condition actually refers to the following two ranges:
1680 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1681 // We can fold these two ranges if:
1682 // 1) C1 and C2 is unsigned greater than C3.
1683 // 2) The two ranges are separated.
1684 // 3) C1 ^ C2 is one-bit mask.
1685 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1686 // This implies all values in the two ranges differ by exactly one bit.
1687
1688 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1689 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1690 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1691 LHSCst->getValue() == (RHSCst->getValue())) {
1692
1693 Value *LAdd = LHS->getOperand(0);
1694 Value *RAdd = RHS->getOperand(0);
1695
1696 Value *LAddOpnd, *RAddOpnd;
1697 ConstantInt *LAddCst, *RAddCst;
1698 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1699 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1700 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1701 RAddCst->getValue().ugt(LHSCst->getValue())) {
1702
1703 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1704 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1705 ConstantInt *MaxAddCst = nullptr;
1706 if (LAddCst->getValue().ult(RAddCst->getValue()))
1707 MaxAddCst = RAddCst;
1708 else
1709 MaxAddCst = LAddCst;
1710
1711 APInt RRangeLow = -RAddCst->getValue();
1712 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1713 APInt LRangeLow = -LAddCst->getValue();
1714 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1715 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1716 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1717 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1718 : RRangeLow - LRangeLow;
1719
1720 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1721 RangeDiff.ugt(LHSCst->getValue())) {
1722 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1723
1724 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1725 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1726 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1727 }
1728 }
1729 }
1730 }
1731
Chris Lattner0a8191e2010-01-05 07:50:36 +00001732 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1733 if (PredicatesFoldable(LHSCC, RHSCC)) {
1734 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1735 LHS->getOperand(1) == RHS->getOperand(0))
1736 LHS->swapOperands();
1737 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1738 LHS->getOperand(1) == RHS->getOperand(1)) {
1739 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1740 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1741 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001742 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001743 }
1744 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001745
1746 // handle (roughly):
1747 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001748 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001749 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001750
Chris Lattner0a8191e2010-01-05 07:50:36 +00001751 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001752 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1753 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1754 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001755 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001756 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1757 B = Val;
1758 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1759 A = Val2;
1760 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1761 A = RHS->getOperand(1);
1762 }
1763 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1764 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1765 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1766 B = Val2;
1767 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1768 A = Val;
1769 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1770 A = LHS->getOperand(1);
1771 }
1772 if (A && B)
1773 return Builder->CreateICmp(
1774 ICmpInst::ICMP_UGE,
1775 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1776 }
1777
Erik Ecksteind1817522014-12-03 10:39:15 +00001778 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1779 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1780 return V;
1781
1782 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1783 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1784 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001785
David Majnemerc2a990b2013-07-05 00:31:17 +00001786 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001787 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001788
Owen Anderson8f306a72010-08-02 09:32:13 +00001789 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1790 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1791 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1792 Value *NewOr = Builder->CreateOr(Val, Val2);
1793 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1794 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001795 }
1796
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001797 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001798 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001799 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001800 ConstantInt *AddCst;
1801 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1802 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001803 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001804 }
1805
Chris Lattner0a8191e2010-01-05 07:50:36 +00001806 // From here on, we only handle:
1807 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001808 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001809
Chris Lattner0a8191e2010-01-05 07:50:36 +00001810 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1811 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1812 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1813 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1814 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001815 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001816
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 // We can't fold (ugt x, C) | (sgt x, C2).
1818 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001819 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001820
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 // Ensure that the larger constant is on the RHS.
1822 bool ShouldSwap;
1823 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001824 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001825 CmpInst::isSigned(RHSCC)))
1826 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1827 else
1828 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001829
Chris Lattner0a8191e2010-01-05 07:50:36 +00001830 if (ShouldSwap) {
1831 std::swap(LHS, RHS);
1832 std::swap(LHSCst, RHSCst);
1833 std::swap(LHSCC, RHSCC);
1834 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001835
Dan Gohman4a618822010-02-10 16:03:48 +00001836 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001837 // comparing a value against two constants and or'ing the result
1838 // together. Because of the above check, we know that we only have
1839 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1840 // icmp folding check above), that the two constants are not
1841 // equal.
1842 assert(LHSCst != RHSCst && "Compares not folded above?");
1843
1844 switch (LHSCC) {
1845 default: llvm_unreachable("Unknown integer condition code!");
1846 case ICmpInst::ICMP_EQ:
1847 switch (RHSCC) {
1848 default: llvm_unreachable("Unknown integer condition code!");
1849 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001850 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001851 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001852 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001853 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1854
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001855 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1856 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00001857 Value *Cst = Builder->getInt(Xor);
1858 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1859 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001860 }
1861 }
1862
David Majnemer1fae1952013-04-14 21:15:43 +00001863 if (LHSCst == SubOne(RHSCst)) {
1864 // (X == 13 | X == 14) -> X-13 <u 2
1865 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1866 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1867 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1868 return Builder->CreateICmpULT(Add, AddCST);
1869 }
1870
Chris Lattner0a8191e2010-01-05 07:50:36 +00001871 break; // (X == 13 | X == 15) -> no change
1872 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1873 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1874 break;
1875 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1876 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1877 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001878 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001879 }
1880 break;
1881 case ICmpInst::ICMP_NE:
1882 switch (RHSCC) {
1883 default: llvm_unreachable("Unknown integer condition code!");
1884 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1885 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1886 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001887 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001888 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1889 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1890 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001891 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001892 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001893 case ICmpInst::ICMP_ULT:
1894 switch (RHSCC) {
1895 default: llvm_unreachable("Unknown integer condition code!");
1896 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1897 break;
1898 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1899 // If RHSCst is [us]MAXINT, it is always false. Not handling
1900 // this can cause overflow.
1901 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001902 return LHS;
Sanjay Patel85d79742016-08-31 19:49:56 +00001903 return insertRangeTest(Val, LHSCst->getValue(), RHSCst->getValue() + 1,
1904 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001905 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1906 break;
1907 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1908 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001909 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1911 break;
1912 }
1913 break;
1914 case ICmpInst::ICMP_SLT:
1915 switch (RHSCC) {
1916 default: llvm_unreachable("Unknown integer condition code!");
1917 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1918 break;
1919 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1920 // If RHSCst is [us]MAXINT, it is always false. Not handling
1921 // this can cause overflow.
1922 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001923 return LHS;
Sanjay Patel85d79742016-08-31 19:49:56 +00001924 return insertRangeTest(Val, LHSCst->getValue(), RHSCst->getValue() + 1,
1925 true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1927 break;
1928 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1929 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001930 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001931 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1932 break;
1933 }
1934 break;
1935 case ICmpInst::ICMP_UGT:
1936 switch (RHSCC) {
1937 default: llvm_unreachable("Unknown integer condition code!");
1938 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1939 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001940 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1942 break;
1943 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1944 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001945 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001946 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1947 break;
1948 }
1949 break;
1950 case ICmpInst::ICMP_SGT:
1951 switch (RHSCC) {
1952 default: llvm_unreachable("Unknown integer condition code!");
1953 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1954 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001955 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001956 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1957 break;
1958 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1959 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001960 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001961 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1962 break;
1963 }
1964 break;
1965 }
Craig Topperf40110f2014-04-25 05:29:35 +00001966 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967}
1968
Sanjay Patel18549272015-09-08 18:24:36 +00001969/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1970/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001971Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001972 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1973 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1974 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1975
1976 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1977 // Swap RHS operands to match LHS.
1978 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1979 std::swap(Op1LHS, Op1RHS);
1980 }
1981
1982 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1983 // This is a similar transformation to the one in FoldAndOfFCmps.
1984 //
1985 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1986 // bool(R & CC0) || bool(R & CC1)
1987 // = bool((R & CC0) | (R & CC1))
1988 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1989 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1990 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1991 Builder);
1992
Chris Lattner0a8191e2010-01-05 07:50:36 +00001993 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001994 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001995 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1996 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1997 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1998 // If either of the constants are nans, then the whole thing returns
1999 // true.
2000 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002001 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002002
Chris Lattner0a8191e2010-01-05 07:50:36 +00002003 // Otherwise, no need to compare the two constants, compare the
2004 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002005 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002006 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002007
Chris Lattner0a8191e2010-01-05 07:50:36 +00002008 // Handle vector zeros. This occurs because the canonical form of
2009 // "fcmp uno x,x" is "fcmp uno x, 0".
2010 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2011 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002012 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002013
Craig Topperf40110f2014-04-25 05:29:35 +00002014 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002015 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002016
Craig Topperf40110f2014-04-25 05:29:35 +00002017 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002018}
2019
Sanjay Patel18549272015-09-08 18:24:36 +00002020/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002021///
2022/// ((A | B) & C1) | (B & C2)
2023///
2024/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002025///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002026/// (A & C1) | B
2027///
2028/// when the XOR of the two constants is "all ones" (-1).
2029Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2030 Value *A, Value *B, Value *C) {
2031 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002032 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002033
Craig Topperf40110f2014-04-25 05:29:35 +00002034 Value *V1 = nullptr;
2035 ConstantInt *CI2 = nullptr;
2036 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037
2038 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002039 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002040
2041 if (V1 == A || V1 == B) {
2042 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2043 return BinaryOperator::CreateOr(NewOp, V1);
2044 }
2045
Craig Topperf40110f2014-04-25 05:29:35 +00002046 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002047}
2048
David Majnemer5d1aeba2014-08-21 05:14:48 +00002049/// \brief This helper function folds:
2050///
2051/// ((A | B) & C1) ^ (B & C2)
2052///
2053/// into:
2054///
2055/// (A & C1) ^ B
2056///
2057/// when the XOR of the two constants is "all ones" (-1).
2058Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2059 Value *A, Value *B, Value *C) {
2060 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2061 if (!CI1)
2062 return nullptr;
2063
2064 Value *V1 = nullptr;
2065 ConstantInt *CI2 = nullptr;
2066 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2067 return nullptr;
2068
2069 APInt Xor = CI1->getValue() ^ CI2->getValue();
2070 if (!Xor.isAllOnesValue())
2071 return nullptr;
2072
2073 if (V1 == A || V1 == B) {
2074 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2075 return BinaryOperator::CreateXor(NewOp, V1);
2076 }
2077
2078 return nullptr;
2079}
2080
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002081// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2082// here. We should standardize that construct where it is needed or choose some
2083// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002084Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002085 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2087
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002088 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002089 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002090
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002091 if (Value *V = SimplifyOrInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002092 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002093
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002094 // (A&B)|(A&C) -> A&(B|C) etc
2095 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002096 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002097
Craig Topper9d4171a2012-12-20 07:09:41 +00002098 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002099 // purpose is to compute bits we don't care about.
2100 if (SimplifyDemandedInstructionBits(I))
2101 return &I;
2102
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002103 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002104 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002105
Chris Lattner0a8191e2010-01-05 07:50:36 +00002106 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002107 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002108 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002109 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002110 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002111 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002112 Op0->hasOneUse()) {
2113 Value *Or = Builder->CreateOr(X, RHS);
2114 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002115 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002116 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002117 }
2118
2119 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2120 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2121 Op0->hasOneUse()) {
2122 Value *Or = Builder->CreateOr(X, RHS);
2123 Or->takeName(Op0);
2124 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002125 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002126 }
2127
2128 // Try to fold constant and into select arguments.
2129 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2130 if (Instruction *R = FoldOpIntoSelect(I, SI))
2131 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002132
Chris Lattner0a8191e2010-01-05 07:50:36 +00002133 if (isa<PHINode>(Op0))
2134 if (Instruction *NV = FoldOpIntoPhi(I))
2135 return NV;
2136 }
2137
Chad Rosiere5819e22016-05-26 14:58:51 +00002138 // Given an OR instruction, check to see if this is a bswap.
2139 if (Instruction *BSwap = MatchBSwap(I))
2140 return BSwap;
2141
Craig Topperf40110f2014-04-25 05:29:35 +00002142 Value *A = nullptr, *B = nullptr;
2143 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002144
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002145 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146 if (Op0->hasOneUse() &&
2147 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002148 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002149 Value *NOr = Builder->CreateOr(A, Op1);
2150 NOr->takeName(Op0);
2151 return BinaryOperator::CreateXor(NOr, C1);
2152 }
2153
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002154 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002155 if (Op1->hasOneUse() &&
2156 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002157 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002158 Value *NOr = Builder->CreateOr(A, Op0);
2159 NOr->takeName(Op0);
2160 return BinaryOperator::CreateXor(NOr, C1);
2161 }
2162
Suyog Sardad64faf62014-07-22 18:09:41 +00002163 // ((~A & B) | A) -> (A | B)
2164 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2165 match(Op1, m_Specific(A)))
2166 return BinaryOperator::CreateOr(A, B);
2167
2168 // ((A & B) | ~A) -> (~A | B)
2169 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2170 match(Op1, m_Not(m_Specific(A))))
2171 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2172
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002173 // (A & ~B) | (A ^ B) -> (A ^ B)
2174 // (~B & A) | (A ^ B) -> (A ^ B)
2175 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda52324c82014-08-01 04:50:31 +00002176 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2177 return BinaryOperator::CreateXor(A, B);
2178
Sanjay Patel5a443ac2016-12-19 18:35:37 +00002179 // Commute the 'or' operands.
2180 // (A ^ B) | (A & ~B) -> (A ^ B)
2181 // (A ^ B) | (~B & A) -> (A ^ B)
2182 if (match(Op1, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2183 match(Op0, m_Xor(m_Specific(A), m_Specific(B))))
Suyog Sarda52324c82014-08-01 04:50:31 +00002184 return BinaryOperator::CreateXor(A, B);
2185
Chris Lattner0a8191e2010-01-05 07:50:36 +00002186 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002187 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002188 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2189 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002190 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002191 C1 = dyn_cast<ConstantInt>(C);
2192 C2 = dyn_cast<ConstantInt>(D);
2193 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002194 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002195 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002196 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002197 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002198 ((V1 == B &&
2199 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2200 (V2 == B &&
2201 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002203 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002204 // Or commutes, try both ways.
2205 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002206 ((V1 == A &&
2207 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2208 (V2 == A &&
2209 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002210 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002211 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002212
Chris Lattner95188692010-01-11 06:55:24 +00002213 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002214 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002215 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002216 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2217 (C3->getValue() & ~C1->getValue()) == 0 &&
2218 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2219 (C4->getValue() & ~C2->getValue()) == 0) {
2220 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2221 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002222 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002223 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002224 }
2225 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002226
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002227 // Don't try to form a select if it's unlikely that we'll get rid of at
2228 // least one of the operands. A select is generally more expensive than the
2229 // 'or' that it is replacing.
2230 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2231 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2232 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2233 return replaceInstUsesWith(I, V);
2234 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2235 return replaceInstUsesWith(I, V);
2236 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2237 return replaceInstUsesWith(I, V);
2238 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2239 return replaceInstUsesWith(I, V);
2240 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2241 return replaceInstUsesWith(I, V);
2242 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2243 return replaceInstUsesWith(I, V);
2244 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2245 return replaceInstUsesWith(I, V);
2246 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2247 return replaceInstUsesWith(I, V);
2248 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002249
2250 // ((A&~B)|(~A&B)) -> A^B
2251 if ((match(C, m_Not(m_Specific(D))) &&
2252 match(B, m_Not(m_Specific(A)))))
2253 return BinaryOperator::CreateXor(A, D);
2254 // ((~B&A)|(~A&B)) -> A^B
2255 if ((match(A, m_Not(m_Specific(D))) &&
2256 match(B, m_Not(m_Specific(C)))))
2257 return BinaryOperator::CreateXor(C, D);
2258 // ((A&~B)|(B&~A)) -> A^B
2259 if ((match(C, m_Not(m_Specific(B))) &&
2260 match(D, m_Not(m_Specific(A)))))
2261 return BinaryOperator::CreateXor(A, B);
2262 // ((~B&A)|(B&~A)) -> A^B
2263 if ((match(A, m_Not(m_Specific(B))) &&
2264 match(D, m_Not(m_Specific(C)))))
2265 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002266
2267 // ((A|B)&1)|(B&-2) -> (A&1) | B
2268 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2269 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2270 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2271 if (Ret) return Ret;
2272 }
2273 // (B&-2)|((A|B)&1) -> (A&1) | B
2274 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2275 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2276 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2277 if (Ret) return Ret;
2278 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002279 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2280 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2281 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2282 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2283 if (Ret) return Ret;
2284 }
2285 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2286 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2287 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2288 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2289 if (Ret) return Ret;
2290 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002291 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002292
David Majnemer42af3602014-07-30 21:26:37 +00002293 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2294 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2295 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2296 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2297 return BinaryOperator::CreateOr(Op0, C);
2298
2299 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2300 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2301 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2302 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2303 return BinaryOperator::CreateOr(Op1, C);
2304
David Majnemerf1eda232014-08-14 06:41:38 +00002305 // ((B | C) & A) | B -> B | (A & C)
2306 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2307 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2308
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002309 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2310 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002311
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002312 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002313 bool SwappedForXor = false;
2314 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002315 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002316 SwappedForXor = true;
2317 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002318
2319 // A | ( A ^ B) -> A | B
2320 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002321 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002322 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2323 if (Op0 == A || Op0 == B)
2324 return BinaryOperator::CreateOr(A, B);
2325
Chad Rosier7813dce2012-04-26 23:29:14 +00002326 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2327 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2328 return BinaryOperator::CreateOr(A, B);
2329
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002330 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2331 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2332 return BinaryOperator::CreateOr(Not, Op0);
2333 }
2334 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2335 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2336 return BinaryOperator::CreateOr(Not, Op0);
2337 }
2338 }
2339
2340 // A | ~(A | B) -> A | ~B
2341 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002342 if (match(Op1, m_Not(m_Value(A))))
2343 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002344 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2345 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2346 B->getOpcode() == Instruction::Xor)) {
2347 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2348 B->getOperand(0);
2349 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2350 return BinaryOperator::CreateOr(Not, Op0);
2351 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002352
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002353 // (A & B) | (~A ^ B) -> (~A ^ B)
2354 // (A & B) | (B ^ ~A) -> (~A ^ B)
2355 // (B & A) | (~A ^ B) -> (~A ^ B)
2356 // (B & A) | (B ^ ~A) -> (~A ^ B)
2357 // The match order is important: match the xor first because the 'not'
2358 // operation defines 'A'. We do not need to match the xor as Op0 because the
2359 // xor was canonicalized to Op1 above.
2360 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2361 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002362 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2363
Eli Friedmane06535b2012-03-16 00:52:42 +00002364 if (SwappedForXor)
2365 std::swap(Op0, Op1);
2366
David Majnemer3d6f80b2014-11-28 19:58:29 +00002367 {
2368 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2369 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2370 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002371 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002372 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002373
David Majnemer3d6f80b2014-11-28 19:58:29 +00002374 // TODO: Make this recursive; it's a little tricky because an arbitrary
2375 // number of 'or' instructions might have to be created.
2376 Value *X, *Y;
2377 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2378 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2379 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002380 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002381 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2382 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002383 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002384 }
2385 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2386 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2387 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002389 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2390 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002391 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002392 }
2393 }
2394
Chris Lattner4e8137d2010-02-11 06:26:33 +00002395 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2396 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2397 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002398 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002400
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002401 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2402 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002403
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002404 // 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 +00002405 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002406 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002407 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002408 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002409 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002410 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2411
Owen Andersonc237a842010-09-13 17:59:27 +00002412 // Note: If we've gotten to the point of visiting the outer OR, then the
2413 // inner one couldn't be simplified. If it was a constant, then it won't
2414 // be simplified by a later pass either, so we try swapping the inner/outer
2415 // ORs in the hopes that we'll be able to simplify it this way.
2416 // (X|C) | V --> (X|V) | C
2417 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2418 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2419 Value *Inner = Builder->CreateOr(A, Op1);
2420 Inner->takeName(Op0);
2421 return BinaryOperator::CreateOr(Inner, C1);
2422 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002423
Bill Wendling23242092013-02-16 23:41:36 +00002424 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2425 // Since this OR statement hasn't been optimized further yet, we hope
2426 // that this transformation will allow the new ORs to be optimized.
2427 {
Craig Topperf40110f2014-04-25 05:29:35 +00002428 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002429 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2430 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2431 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2432 Value *orTrue = Builder->CreateOr(A, C);
2433 Value *orFalse = Builder->CreateOr(B, D);
2434 return SelectInst::Create(X, orTrue, orFalse);
2435 }
2436 }
2437
Craig Topperf40110f2014-04-25 05:29:35 +00002438 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002439}
2440
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002441// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2442// here. We should standardize that construct where it is needed or choose some
2443// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002445 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2447
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002448 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002449 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002450
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002451 if (Value *V = SimplifyXorInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002452 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002454 // (A&B)^(A&C) -> A&(B^C) etc
2455 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002456 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002457
Craig Topper9d4171a2012-12-20 07:09:41 +00002458 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002459 // purpose is to compute bits we don't care about.
2460 if (SimplifyDemandedInstructionBits(I))
2461 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002462
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002463 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002464 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002465
Chris Lattner0a8191e2010-01-05 07:50:36 +00002466 // Is this a ~ operation?
2467 if (Value *NotOp = dyn_castNotVal(&I)) {
2468 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002469 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002470 Op0I->getOpcode() == Instruction::Or) {
2471 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2472 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2473 if (dyn_castNotVal(Op0I->getOperand(1)))
2474 Op0I->swapOperands();
2475 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2476 Value *NotY =
2477 Builder->CreateNot(Op0I->getOperand(1),
2478 Op0I->getOperand(1)->getName()+".not");
2479 if (Op0I->getOpcode() == Instruction::And)
2480 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2481 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2482 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002483
Chris Lattner0a8191e2010-01-05 07:50:36 +00002484 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2485 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002486 if (IsFreeToInvert(Op0I->getOperand(0),
2487 Op0I->getOperand(0)->hasOneUse()) &&
2488 IsFreeToInvert(Op0I->getOperand(1),
2489 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002490 Value *NotX =
2491 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2492 Value *NotY =
2493 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2494 if (Op0I->getOpcode() == Instruction::And)
2495 return BinaryOperator::CreateOr(NotX, NotY);
2496 return BinaryOperator::CreateAnd(NotX, NotY);
2497 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002498
2499 } else if (Op0I->getOpcode() == Instruction::AShr) {
2500 // ~(~X >>s Y) --> (X >>s Y)
2501 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2502 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503 }
2504 }
2505 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002506
Benjamin Kramer443c7962015-02-12 20:26:46 +00002507 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2508 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002510 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2511 return CmpInst::Create(CI->getOpcode(),
2512 CI->getInversePredicate(),
2513 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002514 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515
Benjamin Kramer443c7962015-02-12 20:26:46 +00002516 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002517 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2518 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2519 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2520 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2521 Instruction::CastOps Opcode = Op0C->getOpcode();
2522 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002523 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002524 Op0C->getDestTy()))) {
2525 CI->setPredicate(CI->getInversePredicate());
2526 return CastInst::Create(Opcode, CI, Op0C->getType());
2527 }
2528 }
2529 }
2530 }
2531
2532 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2533 // ~(c-X) == X-c-1 == X+(-c-1)
2534 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2535 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2536 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2537 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2538 ConstantInt::get(I.getType(), 1));
2539 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2540 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002541
Chris Lattner0a8191e2010-01-05 07:50:36 +00002542 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2543 if (Op0I->getOpcode() == Instruction::Add) {
2544 // ~(X-c) --> (-c-1)-X
2545 if (RHS->isAllOnesValue()) {
2546 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2547 return BinaryOperator::CreateSub(
2548 ConstantExpr::getSub(NegOp0CI,
2549 ConstantInt::get(I.getType(), 1)),
2550 Op0I->getOperand(0));
2551 } else if (RHS->getValue().isSignBit()) {
2552 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002553 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2555
2556 }
2557 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002558 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002559 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2560 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002561 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2562 // Anything in both C1 and C2 is known to be zero, remove it from
2563 // NewRHS.
2564 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002565 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002566 ConstantExpr::getNot(CommonBits));
2567 Worklist.Add(Op0I);
2568 I.setOperand(0, Op0I->getOperand(0));
2569 I.setOperand(1, NewRHS);
2570 return &I;
2571 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002572 } else if (Op0I->getOpcode() == Instruction::LShr) {
2573 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2574 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002575 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002576 ConstantInt *C1;
2577 if (Op0I->hasOneUse() &&
2578 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2579 E1->getOpcode() == Instruction::Xor &&
2580 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2581 // fold (C1 >> C2) ^ C3
2582 ConstantInt *C2 = Op0CI, *C3 = RHS;
2583 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2584 FoldConst ^= C3->getValue();
2585 // Prepare the two operands.
2586 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2587 Opnd0->takeName(Op0I);
2588 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2589 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2590
2591 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2592 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002593 }
2594 }
2595 }
2596
2597 // Try to fold constant and into select arguments.
2598 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2599 if (Instruction *R = FoldOpIntoSelect(I, SI))
2600 return R;
2601 if (isa<PHINode>(Op0))
2602 if (Instruction *NV = FoldOpIntoPhi(I))
2603 return NV;
2604 }
2605
Chris Lattner0a8191e2010-01-05 07:50:36 +00002606 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2607 if (Op1I) {
2608 Value *A, *B;
2609 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2610 if (A == Op0) { // B^(B|A) == (A|B)^B
2611 Op1I->swapOperands();
2612 I.swapOperands();
2613 std::swap(Op0, Op1);
2614 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2615 I.swapOperands(); // Simplified below.
2616 std::swap(Op0, Op1);
2617 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002618 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002619 Op1I->hasOneUse()){
2620 if (A == Op0) { // A^(A&B) -> A^(B&A)
2621 Op1I->swapOperands();
2622 std::swap(A, B);
2623 }
2624 if (B == Op0) { // A^(B&A) -> (B&A)^A
2625 I.swapOperands(); // Simplified below.
2626 std::swap(Op0, Op1);
2627 }
2628 }
2629 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002630
Chris Lattner0a8191e2010-01-05 07:50:36 +00002631 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2632 if (Op0I) {
2633 Value *A, *B;
2634 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2635 Op0I->hasOneUse()) {
2636 if (A == Op1) // (B|A)^B == (A|B)^B
2637 std::swap(A, B);
2638 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002639 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002640 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002641 Op0I->hasOneUse()){
2642 if (A == Op1) // (A&B)^A -> (B&A)^A
2643 std::swap(A, B);
2644 if (B == Op1 && // (B&A)^A == ~B & A
2645 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002646 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002647 }
2648 }
2649 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002650
Chris Lattner0a8191e2010-01-05 07:50:36 +00002651 if (Op0I && Op1I) {
2652 Value *A, *B, *C, *D;
2653 // (A & B)^(A | B) -> A ^ B
2654 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2655 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002656 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002657 return BinaryOperator::CreateXor(A, B);
2658 }
2659 // (A | B)^(A & B) -> A ^ B
2660 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2661 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002662 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002663 return BinaryOperator::CreateXor(A, B);
2664 }
David Majnemer698dca02014-08-14 06:46:25 +00002665 // (A | ~B) ^ (~A | B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002666 // (~B | A) ^ (~A | B) -> A ^ B
2667 if (match(Op0I, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2668 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B))))
David Majnemer698dca02014-08-14 06:46:25 +00002669 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002670
David Majnemer698dca02014-08-14 06:46:25 +00002671 // (~A | B) ^ (A | ~B) -> A ^ B
2672 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2673 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2674 return BinaryOperator::CreateXor(A, B);
2675 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002676 // (A & ~B) ^ (~A & B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002677 // (~B & A) ^ (~A & B) -> A ^ B
2678 if (match(Op0I, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2679 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B))))
Mayur Pandey960507b2014-08-19 08:19:19 +00002680 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002681
Mayur Pandey960507b2014-08-19 08:19:19 +00002682 // (~A & B) ^ (A & ~B) -> A ^ B
2683 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2684 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2685 return BinaryOperator::CreateXor(A, B);
2686 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002687 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2688 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2689 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2690 if (D == A)
2691 return BinaryOperator::CreateXor(
2692 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2693 if (D == B)
2694 return BinaryOperator::CreateXor(
2695 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002696 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002697 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002698 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002699 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2700 if (D == A)
2701 return BinaryOperator::CreateXor(
2702 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2703 if (D == B)
2704 return BinaryOperator::CreateXor(
2705 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002706 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002707 // (A & B) ^ (A ^ B) -> (A | B)
2708 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2709 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2710 return BinaryOperator::CreateOr(A, B);
2711 // (A ^ B) ^ (A & B) -> (A | B)
2712 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2713 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2714 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002715 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002716
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002717 // (A & ~B) ^ ~A -> ~(A & B)
2718 // (~B & A) ^ ~A -> ~(A & B)
2719 Value *A, *B;
2720 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002721 match(Op1, m_Not(m_Specific(A))))
2722 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2723
David Majnemerb0761a02016-12-21 19:21:59 +00002724 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002725 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
David Majnemerb0761a02016-12-21 19:21:59 +00002726 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002727 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2728 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2729 LHS->getOperand(1) == RHS->getOperand(0))
2730 LHS->swapOperands();
2731 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2732 LHS->getOperand(1) == RHS->getOperand(1)) {
2733 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2734 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2735 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002736 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002737 getNewICmpValue(isSigned, Code, Op0, Op1,
2738 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002739 }
2740 }
2741
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002742 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2743 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002744
Craig Topperf40110f2014-04-25 05:29:35 +00002745 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002746}