blob: 3865572e8169bf8ccefae84d497583b2653df09d [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.
101 if (I.getType()->isVectorTy()) return nullptr;
102
103 // Can only do bitwise ops.
104 unsigned Op = I.getOpcode();
105 if (Op != Instruction::And && Op != Instruction::Or &&
106 Op != Instruction::Xor)
107 return nullptr;
108
109 Value *OldLHS = I.getOperand(0);
110 Value *OldRHS = I.getOperand(1);
111 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
112 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
113 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
114 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
115 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
116 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
117
118 if (!IsBswapLHS && !IsBswapRHS)
119 return nullptr;
120
121 if (!IsBswapLHS && !ConstLHS)
122 return nullptr;
123
124 if (!IsBswapRHS && !ConstRHS)
125 return nullptr;
126
127 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
128 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
129 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
130 Builder->getInt(ConstLHS->getValue().byteSwap());
131
132 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
133 Builder->getInt(ConstRHS->getValue().byteSwap());
134
135 Value *BinOp = nullptr;
136 if (Op == Instruction::And)
137 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
138 else if (Op == Instruction::Or)
139 BinOp = Builder->CreateOr(NewLHS, NewRHS);
140 else //if (Op == Instruction::Xor)
141 BinOp = Builder->CreateXor(NewLHS, NewRHS);
142
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000143 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000144 return Builder->CreateCall(F, BinOp);
145}
146
Sanjay Patel18549272015-09-08 18:24:36 +0000147/// This handles expressions of the form ((val OP C1) & C2). Where
148/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
149/// guaranteed to be a binary operator.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000150Instruction *InstCombiner::OptAndOp(Instruction *Op,
151 ConstantInt *OpRHS,
152 ConstantInt *AndRHS,
153 BinaryOperator &TheAnd) {
154 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000155 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000156 if (!Op->isShift())
157 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
158
159 switch (Op->getOpcode()) {
160 case Instruction::Xor:
161 if (Op->hasOneUse()) {
162 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
163 Value *And = Builder->CreateAnd(X, AndRHS);
164 And->takeName(Op);
165 return BinaryOperator::CreateXor(And, Together);
166 }
167 break;
168 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000169 if (Op->hasOneUse()){
170 if (Together != OpRHS) {
171 // (X | C1) & C2 --> (X | (C1&C2)) & C2
172 Value *Or = Builder->CreateOr(X, Together);
173 Or->takeName(Op);
174 return BinaryOperator::CreateAnd(Or, AndRHS);
175 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000176
Owen Andersonc237a842010-09-13 17:59:27 +0000177 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
178 if (TogetherCI && !TogetherCI->isZero()){
179 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
180 // NOTE: This reduces the number of bits set in the & mask, which
181 // can expose opportunities for store narrowing.
182 Together = ConstantExpr::getXor(AndRHS, Together);
183 Value *And = Builder->CreateAnd(X, Together);
184 And->takeName(Op);
185 return BinaryOperator::CreateOr(And, OpRHS);
186 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000187 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000188
Chris Lattner0a8191e2010-01-05 07:50:36 +0000189 break;
190 case Instruction::Add:
191 if (Op->hasOneUse()) {
192 // Adding a one to a single bit bit-field should be turned into an XOR
193 // of the bit. First thing to check is to see if this AND is with a
194 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000195 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000196
197 // If there is only one bit set.
198 if (AndRHSV.isPowerOf2()) {
199 // Ok, at this point, we know that we are masking the result of the
200 // ADD down to exactly one bit. If the constant we are adding has
201 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000202 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000203
204 // Check to see if any bits below the one bit set in AndRHSV are set.
205 if ((AddRHS & (AndRHSV-1)) == 0) {
206 // If not, the only thing that can effect the output of the AND is
207 // the bit specified by AndRHSV. If that bit is set, the effect of
208 // the XOR is to toggle the bit. If it is clear, then the ADD has
209 // no effect.
210 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
211 TheAnd.setOperand(0, X);
212 return &TheAnd;
213 } else {
214 // Pull the XOR out of the AND.
215 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
216 NewAnd->takeName(Op);
217 return BinaryOperator::CreateXor(NewAnd, AndRHS);
218 }
219 }
220 }
221 }
222 break;
223
224 case Instruction::Shl: {
225 // We know that the AND will not produce any of the bits shifted in, so if
226 // the anded constant includes them, clear them now!
227 //
228 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
229 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
230 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000231 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000232
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000233 if (CI->getValue() == ShlMask)
234 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000235 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000236
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000237 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000238 TheAnd.setOperand(1, CI);
239 return &TheAnd;
240 }
241 break;
242 }
243 case Instruction::LShr: {
244 // We know that the AND will not produce any of the bits shifted in, so if
245 // the anded constant includes them, clear them now! This only applies to
246 // unsigned shifts, because a signed shr may bring in set bits!
247 //
248 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
249 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
250 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000251 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000252
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000253 if (CI->getValue() == ShrMask)
254 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000255 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000256
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000257 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000258 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
259 return &TheAnd;
260 }
261 break;
262 }
263 case Instruction::AShr:
264 // Signed shr.
265 // See if this is shifting in some sign extension, then masking it out
266 // with an and.
267 if (Op->hasOneUse()) {
268 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
269 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
270 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000271 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000272 if (C == AndRHS) { // Masking out bits shifted in.
273 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
274 // Make the argument unsigned.
275 Value *ShVal = Op->getOperand(0);
276 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
277 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
278 }
279 }
280 break;
281 }
Craig Topperf40110f2014-04-25 05:29:35 +0000282 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283}
284
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
286/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000287/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000288/// whether to treat the V, Lo and HI as signed or not. IB is the location to
289/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000290Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
291 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000292 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000293 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
294 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000295
Chris Lattner0a8191e2010-01-05 07:50:36 +0000296 if (Inside) {
297 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000298 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000299
300 // V >= Min && V < Hi --> V < Hi
301 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000302 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000303 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000304 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000305 }
306
307 // Emit V-Lo <u Hi-Lo
308 Constant *NegLo = ConstantExpr::getNeg(Lo);
309 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
310 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000311 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000312 }
313
314 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000315 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000316
317 // V < Min || V >= Hi -> V > Hi-1
318 Hi = SubOne(cast<ConstantInt>(Hi));
319 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000320 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000321 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000322 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000323 }
324
325 // Emit V-Lo >u Hi-1-Lo
326 // Note that Hi has already had one subtracted from it, above.
327 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
328 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
329 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000330 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000331}
332
Sanjay Patel18549272015-09-08 18:24:36 +0000333/// Returns true iff Val consists of one contiguous run of 1s with any number
334/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
335/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
336/// not, since all 1s are not contiguous.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000337static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
338 const APInt& V = Val->getValue();
339 uint32_t BitWidth = Val->getType()->getBitWidth();
340 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
341
342 // look for the first zero bit after the run of ones
343 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
344 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000345 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000346 return true;
347}
348
Sanjay Patel18549272015-09-08 18:24:36 +0000349/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
350/// whether the operator is a sub. If we can fold one of the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000351///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000352/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
353/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
354/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000355///
356/// return (A +/- B).
357///
358Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
359 ConstantInt *Mask, bool isSub,
360 Instruction &I) {
361 Instruction *LHSI = dyn_cast<Instruction>(LHS);
362 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000363 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000364
365 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
366
367 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000368 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000369 case Instruction::And:
370 if (ConstantExpr::getAnd(N, Mask) == Mask) {
371 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000372 if ((Mask->getValue().countLeadingZeros() +
373 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000374 Mask->getValue().getBitWidth())
375 break;
376
377 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
378 // part, we don't need any explicit masks to take them out of A. If that
379 // is all N is, ignore it.
380 uint32_t MB = 0, ME = 0;
381 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
382 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
383 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000384 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000385 break;
386 }
387 }
Craig Topperf40110f2014-04-25 05:29:35 +0000388 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000389 case Instruction::Or:
390 case Instruction::Xor:
391 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000392 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000393 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
394 && ConstantExpr::getAnd(N, Mask)->isNullValue())
395 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000396 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000397 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000398
Chris Lattner0a8191e2010-01-05 07:50:36 +0000399 if (isSub)
400 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
401 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
402}
403
Owen Anderson3fe002d2010-09-08 22:16:17 +0000404/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000405/// One of A and B is considered the mask, the other the value. This is
406/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000407/// contains only "Mask", then both A and B can be considered masks.
408/// If A is the mask, then it was proven, that (A & C) == C. This
409/// is trivial if C == A, or C == 0. If both A and C are constants, this
410/// proof is also easy.
411/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000412/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000413/// if (A & B) == A, or all bits of A are set in B.
414/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000415/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000416/// if (A & B) == 0, or all bits of A are cleared in B.
417/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000418/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000419/// contain any number of one bits and zero bits.
420/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
421/// The Part "Not" means, that in above descriptions "==" should be replaced
422/// by "!=".
423/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
424/// If the mask A contains a single bit, then the following is equivalent:
425/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
426/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
427enum MaskedICmpType {
428 FoldMskICmp_AMask_AllOnes = 1,
429 FoldMskICmp_AMask_NotAllOnes = 2,
430 FoldMskICmp_BMask_AllOnes = 4,
431 FoldMskICmp_BMask_NotAllOnes = 8,
432 FoldMskICmp_Mask_AllZeroes = 16,
433 FoldMskICmp_Mask_NotAllZeroes = 32,
434 FoldMskICmp_AMask_Mixed = 64,
435 FoldMskICmp_AMask_NotMixed = 128,
436 FoldMskICmp_BMask_Mixed = 256,
437 FoldMskICmp_BMask_NotMixed = 512
438};
439
Sanjay Patel18549272015-09-08 18:24:36 +0000440/// Return the set of pattern classes (from MaskedICmpType)
441/// that (icmp SCC (A & B), C) satisfies.
Craig Topper9d4171a2012-12-20 07:09:41 +0000442static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000443 ICmpInst::Predicate SCC)
444{
445 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
446 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
447 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
448 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000449 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000450 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000451 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000452 BCst->getValue().isPowerOf2());
453 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000454 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000455 // if C is zero, then both A and B qualify as mask
456 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000457 FoldMskICmp_AMask_Mixed |
458 FoldMskICmp_BMask_Mixed)
459 : (FoldMskICmp_Mask_NotAllZeroes |
Owen Anderson3fe002d2010-09-08 22:16:17 +0000460 FoldMskICmp_AMask_NotMixed |
461 FoldMskICmp_BMask_NotMixed));
462 if (icmp_abit)
463 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000464 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000465 : (FoldMskICmp_AMask_AllOnes |
466 FoldMskICmp_AMask_Mixed));
467 if (icmp_bbit)
468 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000469 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000470 : (FoldMskICmp_BMask_AllOnes |
471 FoldMskICmp_BMask_Mixed));
472 return result;
473 }
474 if (A == C) {
475 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
476 FoldMskICmp_AMask_Mixed)
477 : (FoldMskICmp_AMask_NotAllOnes |
478 FoldMskICmp_AMask_NotMixed));
479 if (icmp_abit)
480 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
481 FoldMskICmp_AMask_NotMixed)
482 : (FoldMskICmp_Mask_AllZeroes |
483 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000484 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000485 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000486 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
487 : FoldMskICmp_AMask_NotMixed);
488 }
Craig Topperae48cb22012-12-20 07:15:54 +0000489 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000490 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
491 FoldMskICmp_BMask_Mixed)
492 : (FoldMskICmp_BMask_NotAllOnes |
493 FoldMskICmp_BMask_NotMixed));
494 if (icmp_bbit)
495 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000496 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000497 : (FoldMskICmp_Mask_AllZeroes |
498 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000499 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000500 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000501 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
502 : FoldMskICmp_BMask_NotMixed);
503 }
504 return result;
505}
506
Tim Northoverc0756c42013-09-04 11:57:13 +0000507/// Convert an analysis of a masked ICmp into its equivalent if all boolean
508/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
509/// is adjacent to the corresponding normal flag (recording ==), this just
510/// involves swapping those bits over.
511static unsigned conjugateICmpMask(unsigned Mask) {
512 unsigned NewMask;
513 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
514 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
515 FoldMskICmp_BMask_Mixed))
516 << 1;
517
518 NewMask |=
519 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
520 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
521 FoldMskICmp_BMask_NotMixed))
522 >> 1;
523
524 return NewMask;
525}
526
Sanjay Patel18549272015-09-08 18:24:36 +0000527/// Decompose an icmp into the form ((X & Y) pred Z) if possible.
528/// The returned predicate is either == or !=. Returns false if
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000529/// decomposition fails.
530static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
531 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000532 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
533 if (!C)
534 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000535
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000536 switch (I->getPredicate()) {
537 default:
538 return false;
539 case ICmpInst::ICMP_SLT:
540 // X < 0 is equivalent to (X & SignBit) != 0.
541 if (!C->isZero())
542 return false;
543 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
544 Pred = ICmpInst::ICMP_NE;
545 break;
546 case ICmpInst::ICMP_SGT:
547 // X > -1 is equivalent to (X & SignBit) == 0.
548 if (!C->isAllOnesValue())
549 return false;
550 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
551 Pred = ICmpInst::ICMP_EQ;
552 break;
553 case ICmpInst::ICMP_ULT:
554 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
555 if (!C->getValue().isPowerOf2())
556 return false;
557 Y = ConstantInt::get(I->getContext(), -C->getValue());
558 Pred = ICmpInst::ICMP_EQ;
559 break;
560 case ICmpInst::ICMP_UGT:
561 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
562 if (!(C->getValue() + 1).isPowerOf2())
563 return false;
564 Y = ConstantInt::get(I->getContext(), ~C->getValue());
565 Pred = ICmpInst::ICMP_NE;
566 break;
567 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000568
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000569 X = I->getOperand(0);
570 Z = ConstantInt::getNullValue(C->getType());
571 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000572}
573
Sanjay Patel18549272015-09-08 18:24:36 +0000574/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
575/// Return the set of pattern classes (from MaskedICmpType)
576/// that both LHS and RHS satisfy.
Craig Topper9d4171a2012-12-20 07:09:41 +0000577static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000578 Value*& B, Value*& C,
579 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000580 ICmpInst *LHS, ICmpInst *RHS,
581 ICmpInst::Predicate &LHSCC,
582 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000583 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
584 // vectors are not (yet?) supported
585 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
586
587 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000588 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000589 // and L11 & L12 == L21 & L22. The same goes for RHS.
590 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000591 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000592 // above.
593 Value *L1 = LHS->getOperand(0);
594 Value *L2 = LHS->getOperand(1);
595 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000596 // Check whether the icmp can be decomposed into a bit test.
597 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000598 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000599 } else {
600 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000601 if (!L1->getType()->isIntegerTy()) {
602 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000603 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000604 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
605 // Any icmp can be viewed as being trivially masked; if it allows us to
606 // remove one, it's worth it.
607 L11 = L1;
608 L12 = Constant::getAllOnesValue(L1->getType());
609 }
610
611 if (!L2->getType()->isIntegerTy()) {
612 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000613 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000614 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
615 L21 = L2;
616 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000617 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000618 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000619
620 // Bail if LHS was a icmp that can't be decomposed into an equality.
621 if (!ICmpInst::isEquality(LHSCC))
622 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000623
624 Value *R1 = RHS->getOperand(0);
625 Value *R2 = RHS->getOperand(1);
626 Value *R11,*R12;
627 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000628 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
629 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
630 A = R11; D = R12;
631 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
632 A = R12; D = R11;
633 } else {
634 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000635 }
Craig Topperf40110f2014-04-25 05:29:35 +0000636 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000637 } else if (R1->getType()->isIntegerTy()) {
638 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
639 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000640 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000641 R11 = R1;
642 R12 = Constant::getAllOnesValue(R1->getType());
643 }
644
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000645 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
646 A = R11; D = R12; E = R2; ok = true;
647 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000648 A = R12; D = R11; E = R2; ok = true;
649 }
650 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000651
652 // Bail if RHS was a icmp that can't be decomposed into an equality.
653 if (!ICmpInst::isEquality(RHSCC))
654 return 0;
655
Chad Rosier58919cc2016-05-09 21:37:43 +0000656 // Look for ANDs on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000657 if (!ok && R2->getType()->isIntegerTy()) {
658 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
659 R11 = R2;
660 R12 = Constant::getAllOnesValue(R2->getType());
661 }
662
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000663 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
664 A = R11; D = R12; E = R1; ok = true;
665 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000666 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000667 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000668 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000669 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000670 }
671 if (!ok)
672 return 0;
673
674 if (L11 == A) {
675 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000676 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000677 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000678 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000679 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000680 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000681 B = L21; C = L1;
682 }
683
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000684 unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
685 unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
686 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000687}
Sanjay Patel18549272015-09-08 18:24:36 +0000688
689/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
690/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000691static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
692 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000693 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000694 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000695 unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000696 LHSCC, RHSCC);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000697 if (Mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000698 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
699 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000700
Tim Northoverc0756c42013-09-04 11:57:13 +0000701 // In full generality:
702 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
703 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
704 //
705 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
706 // equivalent to (icmp (A & X) !Op Y).
707 //
708 // Therefore, we can pretend for the rest of this function that we're dealing
709 // with the conjunction, provided we flip the sense of any comparisons (both
710 // input and output).
711
712 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000713 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000714 if (!IsAnd) {
715 // Convert the masking analysis into its equivalent with negated
716 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000717 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000718 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000719
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000720 if (Mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000721 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000722 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000723 Value *NewOr = Builder->CreateOr(B, D);
724 Value *NewAnd = Builder->CreateAnd(A, NewOr);
725 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000726 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000727 // with B and D, having a single bit set.
728 Value *Zero = Constant::getNullValue(A->getType());
729 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000730 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000731 if (Mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000732 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000733 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000734 Value *NewOr = Builder->CreateOr(B, D);
735 Value *NewAnd = Builder->CreateAnd(A, NewOr);
736 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000737 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000738 if (Mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000739 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000740 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000741 Value *NewAnd1 = Builder->CreateAnd(B, D);
742 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
743 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000744 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000745
746 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000747 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000748 // easy cases for now" decision.
749 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000750 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000751 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000752 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000753
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000754 if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000755 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
756 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
757 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
758 // Only valid if one of the masks is a superset of the other (check "B&D" is
759 // the same as either B or D).
760 APInt NewMask = BCst->getValue() & DCst->getValue();
761
762 if (NewMask == BCst->getValue())
763 return LHS;
764 else if (NewMask == DCst->getValue())
765 return RHS;
766 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000767 if (Mask & FoldMskICmp_AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000768 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
769 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
770 // Only valid if one of the masks is a superset of the other (check "B|D" is
771 // the same as either B or D).
772 APInt NewMask = BCst->getValue() | DCst->getValue();
773
774 if (NewMask == BCst->getValue())
775 return LHS;
776 else if (NewMask == DCst->getValue())
777 return RHS;
778 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000779 if (Mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000780 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000781 // We already know that B & C == C && D & E == E.
782 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
783 // C and E, which are shared by both the mask B and the mask D, don't
784 // contradict, then we can transform to
785 // -> (icmp eq (A & (B|D)), (C|E))
786 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000787 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000788 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000789 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000790 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000791 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000792 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000793 if (!ECst) return nullptr;
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000794 if (LHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000795 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000796 if (RHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000797 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000798 // If there is a conflict, we should actually return a false for the
799 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000800 if (((BCst->getValue() & DCst->getValue()) &
801 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000802 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000803 Value *NewOr1 = Builder->CreateOr(B, D);
804 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
805 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
806 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000807 }
Craig Topperf40110f2014-04-25 05:29:35 +0000808 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000809}
810
Erik Ecksteind1817522014-12-03 10:39:15 +0000811/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
812/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
813/// If \p Inverted is true then the check is for the inverted range, e.g.
814/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
815Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
816 bool Inverted) {
817 // Check the lower range comparison, e.g. x >= 0
818 // InstCombine already ensured that if there is a constant it's on the RHS.
819 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
820 if (!RangeStart)
821 return nullptr;
822
823 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
824 Cmp0->getPredicate());
825
826 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
827 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
828 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
829 return nullptr;
830
831 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
832 Cmp1->getPredicate());
833
834 Value *Input = Cmp0->getOperand(0);
835 Value *RangeEnd;
836 if (Cmp1->getOperand(0) == Input) {
837 // For the upper range compare we have: icmp x, n
838 RangeEnd = Cmp1->getOperand(1);
839 } else if (Cmp1->getOperand(1) == Input) {
840 // For the upper range compare we have: icmp n, x
841 RangeEnd = Cmp1->getOperand(0);
842 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
843 } else {
844 return nullptr;
845 }
846
847 // Check the upper range comparison, e.g. x < n
848 ICmpInst::Predicate NewPred;
849 switch (Pred1) {
850 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
851 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
852 default: return nullptr;
853 }
854
855 // This simplification is only valid if the upper range is not negative.
856 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000857 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000858 if (!IsNotNegative)
859 return nullptr;
860
861 if (Inverted)
862 NewPred = ICmpInst::getInversePredicate(NewPred);
863
864 return Builder->CreateICmp(NewPred, Input, RangeEnd);
865}
866
Sanjay Patel18549272015-09-08 18:24:36 +0000867/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000868Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000869 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
870
871 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
872 if (PredicatesFoldable(LHSCC, RHSCC)) {
873 if (LHS->getOperand(0) == RHS->getOperand(1) &&
874 LHS->getOperand(1) == RHS->getOperand(0))
875 LHS->swapOperands();
876 if (LHS->getOperand(0) == RHS->getOperand(0) &&
877 LHS->getOperand(1) == RHS->getOperand(1)) {
878 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
879 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
880 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000881 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000882 }
883 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000884
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000885 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000886 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000887 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000888
Erik Ecksteind1817522014-12-03 10:39:15 +0000889 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
890 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
891 return V;
892
893 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
894 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
895 return V;
896
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
898 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
899 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
900 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000901 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000902
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 if (LHSCst == RHSCst && LHSCC == RHSCC) {
904 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000905 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000906 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000907 if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
908 (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000909 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000910 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 }
912 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000913
Benjamin Kramer101720f2011-04-28 20:09:57 +0000914 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000915 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000916 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000917 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000918 LHS->hasOneUse() && RHS->hasOneUse()) {
919 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000920 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000921
922 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000923 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000924 if (match(Val2, m_Trunc(m_Value(V))) &&
925 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
926 SmallCst = RHSCst;
927 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000928 } else if (match(Val, m_Trunc(m_Value(V))) &&
929 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000930 SmallCst = LHSCst;
931 BigCst = RHSCst;
932 }
933
934 if (SmallCst && BigCst) {
935 unsigned BigBitSize = BigCst->getType()->getBitWidth();
936 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
937
938 // Check that the low bits are zero.
939 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000940 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000941 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
942 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
943 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
944 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
945 }
946 }
947 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000948
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949 // From here on, we only handle:
950 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000951 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000952
Chris Lattner0a8191e2010-01-05 07:50:36 +0000953 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
954 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
955 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
956 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
957 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000958 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000959
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 // We can't fold (ugt x, C) & (sgt x, C2).
961 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000962 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000963
Chris Lattner0a8191e2010-01-05 07:50:36 +0000964 // Ensure that the larger constant is on the RHS.
965 bool ShouldSwap;
966 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000967 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000968 CmpInst::isSigned(RHSCC)))
969 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
970 else
971 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000972
Chris Lattner0a8191e2010-01-05 07:50:36 +0000973 if (ShouldSwap) {
974 std::swap(LHS, RHS);
975 std::swap(LHSCst, RHSCst);
976 std::swap(LHSCC, RHSCC);
977 }
978
Dan Gohman4a618822010-02-10 16:03:48 +0000979 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000980 // comparing a value against two constants and and'ing the result
981 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000982 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
983 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000984 // are not equal and that the larger constant is on the RHS
985 assert(LHSCst != RHSCst && "Compares not folded above?");
986
987 switch (LHSCC) {
988 default: llvm_unreachable("Unknown integer condition code!");
989 case ICmpInst::ICMP_EQ:
990 switch (RHSCC) {
991 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
993 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
994 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000995 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000996 }
997 case ICmpInst::ICMP_NE:
998 switch (RHSCC) {
999 default: llvm_unreachable("Unknown integer condition code!");
1000 case ICmpInst::ICMP_ULT:
1001 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001002 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001003 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1004 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005 break; // (X != 13 & X u< 15) -> no change
1006 case ICmpInst::ICMP_SLT:
1007 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001008 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001009 break; // (X != 13 & X s< 15) -> no change
1010 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1011 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1012 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001013 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001015 // Special case to get the ordering right when the values wrap around
1016 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001017 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001018 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001019 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1020 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1021 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001022 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1023 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024 }
1025 break; // (X != 13 & X != 15) -> no change
1026 }
1027 break;
1028 case ICmpInst::ICMP_ULT:
1029 switch (RHSCC) {
1030 default: llvm_unreachable("Unknown integer condition code!");
1031 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1032 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001033 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001034 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1035 break;
1036 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1037 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001038 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001039 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1040 break;
1041 }
1042 break;
1043 case ICmpInst::ICMP_SLT:
1044 switch (RHSCC) {
1045 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001046 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1047 break;
1048 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1049 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001050 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001051 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1052 break;
1053 }
1054 break;
1055 case ICmpInst::ICMP_UGT:
1056 switch (RHSCC) {
1057 default: llvm_unreachable("Unknown integer condition code!");
1058 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1059 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001060 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001061 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1062 break;
1063 case ICmpInst::ICMP_NE:
1064 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001065 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001066 break; // (X u> 13 & X != 15) -> no change
1067 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001068 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001069 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1070 break;
1071 }
1072 break;
1073 case ICmpInst::ICMP_SGT:
1074 switch (RHSCC) {
1075 default: llvm_unreachable("Unknown integer condition code!");
1076 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1077 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001078 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001079 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1080 break;
1081 case ICmpInst::ICMP_NE:
1082 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001083 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001084 break; // (X s> 13 & X != 15) -> no change
1085 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001086 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001087 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1088 break;
1089 }
1090 break;
1091 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001092
Craig Topperf40110f2014-04-25 05:29:35 +00001093 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001094}
1095
Sanjay Patel18549272015-09-08 18:24:36 +00001096/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1097/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001098Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001099 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1100 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1101 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1102
1103 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1104 // Swap RHS operands to match LHS.
1105 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1106 std::swap(Op1LHS, Op1RHS);
1107 }
1108
1109 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1110 // Suppose the relation between x and y is R, where R is one of
1111 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1112 // testing the desired relations.
1113 //
1114 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1115 // bool(R & CC0) && bool(R & CC1)
1116 // = bool((R & CC0) & (R & CC1))
1117 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1118 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1119 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1120 Builder);
1121
Chris Lattner0a8191e2010-01-05 07:50:36 +00001122 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1123 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001124 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001125 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001126
Chris Lattner0a8191e2010-01-05 07:50:36 +00001127 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1128 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1129 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1130 // If either of the constants are nans, then the whole thing returns
1131 // false.
1132 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001133 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001134 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001135 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001136
Chris Lattner0a8191e2010-01-05 07:50:36 +00001137 // Handle vector zeros. This occurs because the canonical form of
1138 // "fcmp ord x,x" is "fcmp ord x, 0".
1139 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1140 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001141 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001142 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001144
Craig Topperf40110f2014-04-25 05:29:35 +00001145 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001146}
1147
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001148/// Match De Morgan's Laws:
1149/// (~A & ~B) == (~(A | B))
1150/// (~A | ~B) == (~(A & B))
1151static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1152 InstCombiner::BuilderTy *Builder) {
1153 auto Opcode = I.getOpcode();
1154 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1155 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001156 // Flip the logic operation.
1157 if (Opcode == Instruction::And)
1158 Opcode = Instruction::Or;
1159 else
1160 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001161
1162 Value *Op0 = I.getOperand(0);
1163 Value *Op1 = I.getOperand(1);
1164 // TODO: Use pattern matchers instead of dyn_cast.
1165 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1166 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1167 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001168 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1169 I.getName() + ".demorgan");
1170 return BinaryOperator::CreateNot(LogicOp);
1171 }
1172
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001173 // De Morgan's Law in disguise:
1174 // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1175 // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1176 Value *A = nullptr;
1177 Value *B = nullptr;
1178 ConstantInt *C1 = nullptr;
1179 if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1180 match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1181 // TODO: This check could be loosened to handle different type sizes.
1182 // Alternatively, we could fix the definition of m_Not to recognize a not
1183 // operation hidden by a zext?
1184 if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1185 C1->isOne()) {
1186 Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1187 I.getName() + ".demorgan");
1188 Value *Not = Builder->CreateNot(LogicOp);
1189 return CastInst::CreateZExtOrBitCast(Not, I.getType());
1190 }
1191 }
1192
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001193 return nullptr;
1194}
1195
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001196Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001197 auto LogicOpc = I.getOpcode();
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001198 assert((LogicOpc == Instruction::And || LogicOpc == Instruction::Or ||
1199 LogicOpc == Instruction::Xor) &&
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001200 "Unexpected opcode for bitwise logic folding");
1201
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001203 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001204 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001205 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001206
Sanjay Patel9bba7502016-03-03 19:19:04 +00001207 // This must be a cast from an integer or integer vector source type to allow
1208 // transformation of the logic operation to the source type.
1209 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001210 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001211 if (!SrcTy->isIntOrIntVectorTy())
1212 return nullptr;
1213
1214 // If one operand is a bitcast and the other is a constant, move the logic
1215 // operation ahead of the bitcast. That is, do the logic operation in the
1216 // original type. This can eliminate useless bitcasts and allow normal
1217 // combines that would otherwise be impeded by the bitcast. Canonicalization
1218 // ensures that if there is a constant operand, it will be the second operand.
1219 Value *BC = nullptr;
1220 Constant *C = nullptr;
1221 if ((match(Op0, m_BitCast(m_Value(BC))) && match(Op1, m_Constant(C)))) {
Sanjay Patel4520d9a2016-06-30 14:27:41 +00001222 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001223 Value *NewOp = Builder->CreateBinOp(LogicOpc, BC, NewConstant, I.getName());
1224 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1225 }
1226
1227 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1228 if (!Cast1)
1229 return nullptr;
1230
1231 // Both operands of the logic operation are casts. The casts must be of the
1232 // same type for reduction.
1233 auto CastOpcode = Cast0->getOpcode();
1234 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001235 return nullptr;
1236
1237 Value *Cast0Src = Cast0->getOperand(0);
1238 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001239
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001240 // fold (logic (cast A), (cast B)) -> (cast (logic A, B))
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001241
Sanjay Patel713f25e2016-02-23 17:41:34 +00001242 // Only do this if the casts both really cause code to be generated.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001243 if ((!isa<ICmpInst>(Cast0Src) || !isa<ICmpInst>(Cast1Src)) &&
1244 ShouldOptimizeCast(CastOpcode, Cast0Src, DestTy) &&
Sanjay Patel713f25e2016-02-23 17:41:34 +00001245 ShouldOptimizeCast(CastOpcode, Cast1Src, DestTy)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001246 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1247 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001248 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001249 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001250
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001251 // For now, only 'and'/'or' have optimizations after this.
1252 if (LogicOpc == Instruction::Xor)
1253 return nullptr;
1254
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001255 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001256 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001257 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1258 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1259 if (ICmp0 && ICmp1) {
1260 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1261 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1262 if (Res)
1263 return CastInst::Create(CastOpcode, Res, DestTy);
1264 return nullptr;
1265 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001266
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001267 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001268 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001269 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1270 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1271 if (FCmp0 && FCmp1) {
1272 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1273 : FoldOrOfFCmps(FCmp0, FCmp1);
1274 if (Res)
1275 return CastInst::Create(CastOpcode, Res, DestTy);
1276 return nullptr;
1277 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001278
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001279 return nullptr;
1280}
1281
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001282static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1284
1285 // Canonicalize SExt or Not to the LHS
1286 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1287 std::swap(Op0, Op1);
1288 }
1289
1290 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1291 Value *X = nullptr;
1292 if (match(Op0, m_SExt(m_Value(X))) &&
1293 X->getType()->getScalarType()->isIntegerTy(1)) {
1294 Value *Zero = Constant::getNullValue(Op1->getType());
1295 return SelectInst::Create(X, Op1, Zero);
1296 }
1297
1298 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1299 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1300 X->getType()->getScalarType()->isIntegerTy(1)) {
1301 Value *Zero = Constant::getNullValue(Op0->getType());
1302 return SelectInst::Create(X, Zero, Op1);
1303 }
1304
1305 return nullptr;
1306}
1307
Chris Lattner0a8191e2010-01-05 07:50:36 +00001308Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001309 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1311
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001312 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001313 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001314
Chandler Carruth66b31302015-01-04 12:03:27 +00001315 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001316 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001317
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001318 // (A|B)&(A|C) -> A|(B&C) etc
1319 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001320 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001321
Craig Topper9d4171a2012-12-20 07:09:41 +00001322 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001323 // purpose is to compute bits we don't care about.
1324 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001325 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001326
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001327 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001329
Chris Lattner0a8191e2010-01-05 07:50:36 +00001330 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1331 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001332
1333 // Optimize a variety of ((val OP C1) & C2) combinations...
1334 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1335 Value *Op0LHS = Op0I->getOperand(0);
1336 Value *Op0RHS = Op0I->getOperand(1);
1337 switch (Op0I->getOpcode()) {
1338 default: break;
1339 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001340 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001341 // If the mask is only needed on one incoming arm, push it up.
1342 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001343
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001344 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001345 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346 // Not masking anything out for the LHS, move to RHS.
1347 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1348 Op0RHS->getName()+".masked");
1349 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1350 }
1351 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001352 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001353 // Not masking anything out for the RHS, move to LHS.
1354 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1355 Op0LHS->getName()+".masked");
1356 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1357 }
1358
1359 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001360 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001361 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001362 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1363 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1364 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001365 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1366 return BinaryOperator::CreateAnd(V, AndRHS);
1367 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1368 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1369 break;
1370
1371 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001372 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1373 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1374 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001375 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1376 return BinaryOperator::CreateAnd(V, AndRHS);
1377
Balaram Makamccf59732015-08-20 15:35:00 +00001378 // -x & 1 -> x & 1
1379 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1380 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1381
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001382 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001383 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001384 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 uint32_t BitWidth = AndRHSMask.getBitWidth();
1386 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1387 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1388
Hal Finkel60db0582014-09-07 18:57:58 +00001389 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001390 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1391 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1392 }
1393 }
1394 break;
1395
1396 case Instruction::Shl:
1397 case Instruction::LShr:
1398 // (1 << x) & 1 --> zext(x == 0)
1399 // (1 >> x) & 1 --> zext(x == 0)
1400 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1401 Value *NewICmp =
1402 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1403 return new ZExtInst(NewICmp, I.getType());
1404 }
1405 break;
1406 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001407
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1409 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1410 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001411 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001412
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001413 // If this is an integer truncation, and if the source is an 'and' with
1414 // immediate, transform it. This frequently occurs for bitfield accesses.
1415 {
Craig Topperf40110f2014-04-25 05:29:35 +00001416 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001417 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1418 // Change: and (trunc (and X, YC) to T), C2
1419 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001420 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001421 // other simplifications.
1422 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1423 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1424 C3 = ConstantExpr::getAnd(C3, AndRHS);
1425 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001426 }
1427 }
1428
1429 // Try to fold constant and into select arguments.
1430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1431 if (Instruction *R = FoldOpIntoSelect(I, SI))
1432 return R;
1433 if (isa<PHINode>(Op0))
1434 if (Instruction *NV = FoldOpIntoPhi(I))
1435 return NV;
1436 }
1437
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001438 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1439 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001440
Chris Lattner0a8191e2010-01-05 07:50:36 +00001441 {
Craig Topperf40110f2014-04-25 05:29:35 +00001442 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001443 // (A|B) & ~(A&B) -> A^B
1444 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1445 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1446 ((A == C && B == D) || (A == D && B == C)))
1447 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001448
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449 // ~(A&B) & (A|B) -> A^B
1450 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1451 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1452 ((A == C && B == D) || (A == D && B == C)))
1453 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001454
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001455 // A&(A^B) => A & ~B
1456 {
1457 Value *tmpOp0 = Op0;
1458 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001459 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001460 if (A == Op1 || B == Op1 ) {
1461 tmpOp1 = Op0;
1462 tmpOp0 = Op1;
1463 // Simplify below
1464 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001465 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001466
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001467 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001468 if (B == tmpOp0) {
1469 std::swap(A, B);
1470 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001471 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001472 // A is originally -1 (or a vector of -1 and undefs), then we enter
1473 // an endless loop. By checking that A is non-constant we ensure that
1474 // we will never get to the loop.
1475 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001476 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001477 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001478 }
1479
1480 // (A&((~A)|B)) -> A&B
1481 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1482 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1483 return BinaryOperator::CreateAnd(A, Op1);
1484 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1485 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1486 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001487
1488 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1489 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1490 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1491 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1492 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1493
1494 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1495 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1496 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1497 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1498 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001499
1500 // (A | B) & ((~A) ^ B) -> (A & B)
1501 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1502 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1503 return BinaryOperator::CreateAnd(A, B);
1504
1505 // ((~A) ^ B) & (A | B) -> (A & B)
1506 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1507 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1508 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001509 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001510
David Majnemer5e96f1b2014-08-30 06:18:20 +00001511 {
1512 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1513 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1514 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001515 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001516 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001517
David Majnemer5e96f1b2014-08-30 06:18:20 +00001518 // TODO: Make this recursive; it's a little tricky because an arbitrary
1519 // number of 'and' instructions might have to be created.
1520 Value *X, *Y;
1521 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1522 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1523 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001524 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001525 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1526 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001527 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001528 }
1529 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1530 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1531 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001532 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001533 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1534 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001535 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001536 }
1537 }
1538
Chris Lattner4e8137d2010-02-11 06:26:33 +00001539 // If and'ing two fcmp, try combine them into one.
1540 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1541 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001542 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001543 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001544
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001545 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1546 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001547
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001548 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1549 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001550
Craig Topperf40110f2014-04-25 05:29:35 +00001551 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001552}
1553
Chad Rosiera00df492016-05-25 16:22:14 +00001554/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1555/// insert the new intrinsic and return it.
1556Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1558
1559 // Look through zero extends.
1560 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1561 Op0 = Ext->getOperand(0);
1562
1563 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1564 Op1 = Ext->getOperand(0);
1565
1566 // (A | B) | C and A | (B | C) -> bswap if possible.
1567 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1568 match(Op1, m_Or(m_Value(), m_Value()));
1569
1570 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1571 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1572 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1573
1574 // (A & B) | (C & D) -> bswap if possible.
1575 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1576 match(Op1, m_And(m_Value(), m_Value()));
1577
1578 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1579 return nullptr;
1580
James Molloyf01488e2016-01-15 09:20:19 +00001581 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001582 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001583 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001584 Instruction *LastInst = Insts.pop_back_val();
1585 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001586
James Molloyf01488e2016-01-15 09:20:19 +00001587 for (auto *Inst : Insts)
1588 Worklist.Add(Inst);
1589 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001590}
1591
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001592/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1593/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1594/// B, it can be used as the condition operand of a select instruction.
1595static Value *getSelectCondition(Value *A, Value *B) {
1596 // If these are scalars or vectors of i1, A can be used directly.
1597 Type *Ty = A->getType();
1598 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1599 return A;
1600
1601 // If A and B are sign-extended, look through the sexts to find the booleans.
1602 Value *Cond;
1603 if (match(A, m_SExt(m_Value(Cond))) &&
1604 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1605 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1606 m_SExt(m_Not(m_Specific(Cond))))))
1607 return Cond;
1608
1609 // TODO: Try more matches that only apply to non-splat constant vectors.
1610
1611 return nullptr;
1612}
1613
1614/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1615/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001616static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001617 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001618 // The potential condition of the select may be bitcasted. In that case, look
1619 // through its bitcast and the corresponding bitcast of the 'not' condition.
1620 Type *OrigType = A->getType();
1621 Value *SrcA, *SrcB;
1622 if (match(A, m_BitCast(m_Value(SrcA))) &&
1623 match(B, m_BitCast(m_Value(SrcB)))) {
1624 A = SrcA;
1625 B = SrcB;
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001626 }
1627
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001628 if (Value *Cond = getSelectCondition(A, B)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001629 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001630 // The bitcasts will either all exist or all not exist. The builder will
1631 // not create unnecessary casts if the types already match.
1632 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1633 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1634 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1635 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001636 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001637
Craig Topperf40110f2014-04-25 05:29:35 +00001638 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001639}
1640
Sanjay Patel18549272015-09-08 18:24:36 +00001641/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001642Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1643 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001644 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1645
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001646 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1647 // if K1 and K2 are a one-bit mask.
1648 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1649 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1650
1651 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1652 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1653
1654 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1655 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1656 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1657 LAnd->getOpcode() == Instruction::And &&
1658 RAnd->getOpcode() == Instruction::And) {
1659
Craig Topperf40110f2014-04-25 05:29:35 +00001660 Value *Mask = nullptr;
1661 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001662 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001663 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1664 DT) &&
1665 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1666 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001667 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1668 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1669 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001670 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1671 CxtI, DT) &&
1672 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1673 CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001674 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1675 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1676 }
1677
1678 if (Masked)
1679 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1680 }
1681 }
1682
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001683 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1684 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1685 // The original condition actually refers to the following two ranges:
1686 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1687 // We can fold these two ranges if:
1688 // 1) C1 and C2 is unsigned greater than C3.
1689 // 2) The two ranges are separated.
1690 // 3) C1 ^ C2 is one-bit mask.
1691 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1692 // This implies all values in the two ranges differ by exactly one bit.
1693
1694 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1695 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1696 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1697 LHSCst->getValue() == (RHSCst->getValue())) {
1698
1699 Value *LAdd = LHS->getOperand(0);
1700 Value *RAdd = RHS->getOperand(0);
1701
1702 Value *LAddOpnd, *RAddOpnd;
1703 ConstantInt *LAddCst, *RAddCst;
1704 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1705 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1706 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1707 RAddCst->getValue().ugt(LHSCst->getValue())) {
1708
1709 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1710 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1711 ConstantInt *MaxAddCst = nullptr;
1712 if (LAddCst->getValue().ult(RAddCst->getValue()))
1713 MaxAddCst = RAddCst;
1714 else
1715 MaxAddCst = LAddCst;
1716
1717 APInt RRangeLow = -RAddCst->getValue();
1718 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1719 APInt LRangeLow = -LAddCst->getValue();
1720 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1721 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1722 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1723 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1724 : RRangeLow - LRangeLow;
1725
1726 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1727 RangeDiff.ugt(LHSCst->getValue())) {
1728 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1729
1730 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1731 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1732 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1733 }
1734 }
1735 }
1736 }
1737
Chris Lattner0a8191e2010-01-05 07:50:36 +00001738 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1739 if (PredicatesFoldable(LHSCC, RHSCC)) {
1740 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1741 LHS->getOperand(1) == RHS->getOperand(0))
1742 LHS->swapOperands();
1743 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1744 LHS->getOperand(1) == RHS->getOperand(1)) {
1745 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1746 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1747 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001748 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001749 }
1750 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001751
1752 // handle (roughly):
1753 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001754 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001755 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001756
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001758 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1759 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1760 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001761 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001762 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1763 B = Val;
1764 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1765 A = Val2;
1766 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1767 A = RHS->getOperand(1);
1768 }
1769 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1770 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1771 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1772 B = Val2;
1773 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1774 A = Val;
1775 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1776 A = LHS->getOperand(1);
1777 }
1778 if (A && B)
1779 return Builder->CreateICmp(
1780 ICmpInst::ICMP_UGE,
1781 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1782 }
1783
Erik Ecksteind1817522014-12-03 10:39:15 +00001784 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1785 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1786 return V;
1787
1788 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1789 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1790 return V;
1791
David Majnemerc2a990b2013-07-05 00:31:17 +00001792 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001793 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794
Owen Anderson8f306a72010-08-02 09:32:13 +00001795 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1796 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1797 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1798 Value *NewOr = Builder->CreateOr(Val, Val2);
1799 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1800 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001801 }
1802
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001803 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001804 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001805 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001806 ConstantInt *AddCst;
1807 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1808 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001809 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001810 }
1811
Chris Lattner0a8191e2010-01-05 07:50:36 +00001812 // From here on, we only handle:
1813 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001814 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001815
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1817 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1818 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1819 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1820 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001821 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001822
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 // We can't fold (ugt x, C) | (sgt x, C2).
1824 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001825 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001826
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 // Ensure that the larger constant is on the RHS.
1828 bool ShouldSwap;
1829 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001830 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831 CmpInst::isSigned(RHSCC)))
1832 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1833 else
1834 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001835
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836 if (ShouldSwap) {
1837 std::swap(LHS, RHS);
1838 std::swap(LHSCst, RHSCst);
1839 std::swap(LHSCC, RHSCC);
1840 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001841
Dan Gohman4a618822010-02-10 16:03:48 +00001842 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001843 // comparing a value against two constants and or'ing the result
1844 // together. Because of the above check, we know that we only have
1845 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1846 // icmp folding check above), that the two constants are not
1847 // equal.
1848 assert(LHSCst != RHSCst && "Compares not folded above?");
1849
1850 switch (LHSCC) {
1851 default: llvm_unreachable("Unknown integer condition code!");
1852 case ICmpInst::ICMP_EQ:
1853 switch (RHSCC) {
1854 default: llvm_unreachable("Unknown integer condition code!");
1855 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001856 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001857 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001858 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001859 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1860
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001861 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1862 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00001863 Value *Cst = Builder->getInt(Xor);
1864 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1865 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001866 }
1867 }
1868
David Majnemer1fae1952013-04-14 21:15:43 +00001869 if (LHSCst == SubOne(RHSCst)) {
1870 // (X == 13 | X == 14) -> X-13 <u 2
1871 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1872 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1873 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1874 return Builder->CreateICmpULT(Add, AddCST);
1875 }
1876
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 break; // (X == 13 | X == 15) -> no change
1878 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1879 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1880 break;
1881 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1882 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1883 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001884 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 }
1886 break;
1887 case ICmpInst::ICMP_NE:
1888 switch (RHSCC) {
1889 default: llvm_unreachable("Unknown integer condition code!");
1890 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1891 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1892 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001893 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001894 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1895 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1896 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001897 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001898 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001899 case ICmpInst::ICMP_ULT:
1900 switch (RHSCC) {
1901 default: llvm_unreachable("Unknown integer condition code!");
1902 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1903 break;
1904 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1905 // If RHSCst is [us]MAXINT, it is always false. Not handling
1906 // this can cause overflow.
1907 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001908 return LHS;
1909 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1911 break;
1912 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1913 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001914 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001915 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1916 break;
1917 }
1918 break;
1919 case ICmpInst::ICMP_SLT:
1920 switch (RHSCC) {
1921 default: llvm_unreachable("Unknown integer condition code!");
1922 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1923 break;
1924 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1925 // If RHSCst is [us]MAXINT, it is always false. Not handling
1926 // this can cause overflow.
1927 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001928 return LHS;
1929 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001930 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1931 break;
1932 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1933 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001934 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001935 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1936 break;
1937 }
1938 break;
1939 case ICmpInst::ICMP_UGT:
1940 switch (RHSCC) {
1941 default: llvm_unreachable("Unknown integer condition code!");
1942 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1943 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001944 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001945 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1946 break;
1947 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1948 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001949 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001950 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1951 break;
1952 }
1953 break;
1954 case ICmpInst::ICMP_SGT:
1955 switch (RHSCC) {
1956 default: llvm_unreachable("Unknown integer condition code!");
1957 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1958 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001959 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001960 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1961 break;
1962 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1963 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001964 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001965 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1966 break;
1967 }
1968 break;
1969 }
Craig Topperf40110f2014-04-25 05:29:35 +00001970 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001971}
1972
Sanjay Patel18549272015-09-08 18:24:36 +00001973/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1974/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001975Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001976 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1977 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1978 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1979
1980 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1981 // Swap RHS operands to match LHS.
1982 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1983 std::swap(Op1LHS, Op1RHS);
1984 }
1985
1986 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1987 // This is a similar transformation to the one in FoldAndOfFCmps.
1988 //
1989 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1990 // bool(R & CC0) || bool(R & CC1)
1991 // = bool((R & CC0) | (R & CC1))
1992 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1993 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1994 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1995 Builder);
1996
Chris Lattner0a8191e2010-01-05 07:50:36 +00001997 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001998 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001999 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2000 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2001 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2002 // If either of the constants are nans, then the whole thing returns
2003 // true.
2004 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002005 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002006
Chris Lattner0a8191e2010-01-05 07:50:36 +00002007 // Otherwise, no need to compare the two constants, compare the
2008 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002009 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002010 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002011
Chris Lattner0a8191e2010-01-05 07:50:36 +00002012 // Handle vector zeros. This occurs because the canonical form of
2013 // "fcmp uno x,x" is "fcmp uno x, 0".
2014 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2015 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002016 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002017
Craig Topperf40110f2014-04-25 05:29:35 +00002018 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002019 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002020
Craig Topperf40110f2014-04-25 05:29:35 +00002021 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002022}
2023
Sanjay Patel18549272015-09-08 18:24:36 +00002024/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025///
2026/// ((A | B) & C1) | (B & C2)
2027///
2028/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002029///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002030/// (A & C1) | B
2031///
2032/// when the XOR of the two constants is "all ones" (-1).
2033Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2034 Value *A, Value *B, Value *C) {
2035 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002036 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037
Craig Topperf40110f2014-04-25 05:29:35 +00002038 Value *V1 = nullptr;
2039 ConstantInt *CI2 = nullptr;
2040 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041
2042 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002043 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002044
2045 if (V1 == A || V1 == B) {
2046 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2047 return BinaryOperator::CreateOr(NewOp, V1);
2048 }
2049
Craig Topperf40110f2014-04-25 05:29:35 +00002050 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051}
2052
David Majnemer5d1aeba2014-08-21 05:14:48 +00002053/// \brief This helper function folds:
2054///
2055/// ((A | B) & C1) ^ (B & C2)
2056///
2057/// into:
2058///
2059/// (A & C1) ^ B
2060///
2061/// when the XOR of the two constants is "all ones" (-1).
2062Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2063 Value *A, Value *B, Value *C) {
2064 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2065 if (!CI1)
2066 return nullptr;
2067
2068 Value *V1 = nullptr;
2069 ConstantInt *CI2 = nullptr;
2070 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2071 return nullptr;
2072
2073 APInt Xor = CI1->getValue() ^ CI2->getValue();
2074 if (!Xor.isAllOnesValue())
2075 return nullptr;
2076
2077 if (V1 == A || V1 == B) {
2078 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2079 return BinaryOperator::CreateXor(NewOp, V1);
2080 }
2081
2082 return nullptr;
2083}
2084
Chris Lattner0a8191e2010-01-05 07:50:36 +00002085Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002086 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2088
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002089 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002090 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002091
Chandler Carruth66b31302015-01-04 12:03:27 +00002092 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002093 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002094
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002095 // (A&B)|(A&C) -> A&(B|C) etc
2096 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002097 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002098
Craig Topper9d4171a2012-12-20 07:09:41 +00002099 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002100 // purpose is to compute bits we don't care about.
2101 if (SimplifyDemandedInstructionBits(I))
2102 return &I;
2103
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002104 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002105 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002106
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002108 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002109 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002110 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002111 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002112 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002113 Op0->hasOneUse()) {
2114 Value *Or = Builder->CreateOr(X, RHS);
2115 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002116 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002117 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002118 }
2119
2120 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2121 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2122 Op0->hasOneUse()) {
2123 Value *Or = Builder->CreateOr(X, RHS);
2124 Or->takeName(Op0);
2125 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002126 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002127 }
2128
2129 // Try to fold constant and into select arguments.
2130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2131 if (Instruction *R = FoldOpIntoSelect(I, SI))
2132 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002133
Chris Lattner0a8191e2010-01-05 07:50:36 +00002134 if (isa<PHINode>(Op0))
2135 if (Instruction *NV = FoldOpIntoPhi(I))
2136 return NV;
2137 }
2138
Chad Rosiere5819e22016-05-26 14:58:51 +00002139 // Given an OR instruction, check to see if this is a bswap.
2140 if (Instruction *BSwap = MatchBSwap(I))
2141 return BSwap;
2142
Craig Topperf40110f2014-04-25 05:29:35 +00002143 Value *A = nullptr, *B = nullptr;
2144 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002145
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002146 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002147 if (Op0->hasOneUse() &&
2148 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002149 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002150 Value *NOr = Builder->CreateOr(A, Op1);
2151 NOr->takeName(Op0);
2152 return BinaryOperator::CreateXor(NOr, C1);
2153 }
2154
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002155 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002156 if (Op1->hasOneUse() &&
2157 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002158 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002159 Value *NOr = Builder->CreateOr(A, Op0);
2160 NOr->takeName(Op0);
2161 return BinaryOperator::CreateXor(NOr, C1);
2162 }
2163
Suyog Sardad64faf62014-07-22 18:09:41 +00002164 // ((~A & B) | A) -> (A | B)
2165 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2166 match(Op1, m_Specific(A)))
2167 return BinaryOperator::CreateOr(A, B);
2168
2169 // ((A & B) | ~A) -> (~A | B)
2170 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2171 match(Op1, m_Not(m_Specific(A))))
2172 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2173
Suyog Sarda52324c82014-08-01 04:50:31 +00002174 // (A & (~B)) | (A ^ B) -> (A ^ B)
2175 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2176 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2177 return BinaryOperator::CreateXor(A, B);
2178
2179 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2180 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2181 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2182 return BinaryOperator::CreateXor(A, B);
2183
Chris Lattner0a8191e2010-01-05 07:50:36 +00002184 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002185 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002186 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2187 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002188 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002189 C1 = dyn_cast<ConstantInt>(C);
2190 C2 = dyn_cast<ConstantInt>(D);
2191 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002192 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002193 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002194 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002195 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002196 ((V1 == B &&
2197 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2198 (V2 == B &&
2199 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002200 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002201 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 // Or commutes, try both ways.
2203 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002204 ((V1 == A &&
2205 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2206 (V2 == A &&
2207 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002208 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002209 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002210
Chris Lattner95188692010-01-11 06:55:24 +00002211 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002212 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002213 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002214 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2215 (C3->getValue() & ~C1->getValue()) == 0 &&
2216 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2217 (C4->getValue() & ~C2->getValue()) == 0) {
2218 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2219 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002220 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002221 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002222 }
2223 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002224
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002225 // Don't try to form a select if it's unlikely that we'll get rid of at
2226 // least one of the operands. A select is generally more expensive than the
2227 // 'or' that it is replacing.
2228 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2229 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2230 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2231 return replaceInstUsesWith(I, V);
2232 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2233 return replaceInstUsesWith(I, V);
2234 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2235 return replaceInstUsesWith(I, V);
2236 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2237 return replaceInstUsesWith(I, V);
2238 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2239 return replaceInstUsesWith(I, V);
2240 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2241 return replaceInstUsesWith(I, V);
2242 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2243 return replaceInstUsesWith(I, V);
2244 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2245 return replaceInstUsesWith(I, V);
2246 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002247
2248 // ((A&~B)|(~A&B)) -> A^B
2249 if ((match(C, m_Not(m_Specific(D))) &&
2250 match(B, m_Not(m_Specific(A)))))
2251 return BinaryOperator::CreateXor(A, D);
2252 // ((~B&A)|(~A&B)) -> A^B
2253 if ((match(A, m_Not(m_Specific(D))) &&
2254 match(B, m_Not(m_Specific(C)))))
2255 return BinaryOperator::CreateXor(C, D);
2256 // ((A&~B)|(B&~A)) -> A^B
2257 if ((match(C, m_Not(m_Specific(B))) &&
2258 match(D, m_Not(m_Specific(A)))))
2259 return BinaryOperator::CreateXor(A, B);
2260 // ((~B&A)|(B&~A)) -> A^B
2261 if ((match(A, m_Not(m_Specific(B))) &&
2262 match(D, m_Not(m_Specific(C)))))
2263 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002264
2265 // ((A|B)&1)|(B&-2) -> (A&1) | B
2266 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2267 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2268 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2269 if (Ret) return Ret;
2270 }
2271 // (B&-2)|((A|B)&1) -> (A&1) | B
2272 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2273 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2274 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2275 if (Ret) return Ret;
2276 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002277 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2278 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2279 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2280 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2281 if (Ret) return Ret;
2282 }
2283 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2284 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2285 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2286 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2287 if (Ret) return Ret;
2288 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002290
David Majnemer42af3602014-07-30 21:26:37 +00002291 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2292 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2293 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2294 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2295 return BinaryOperator::CreateOr(Op0, C);
2296
2297 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2298 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2299 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2300 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2301 return BinaryOperator::CreateOr(Op1, C);
2302
David Majnemerf1eda232014-08-14 06:41:38 +00002303 // ((B | C) & A) | B -> B | (A & C)
2304 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2305 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2306
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002307 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2308 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002309
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002310 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002311 bool SwappedForXor = false;
2312 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002313 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002314 SwappedForXor = true;
2315 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002316
2317 // A | ( A ^ B) -> A | B
2318 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002319 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002320 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2321 if (Op0 == A || Op0 == B)
2322 return BinaryOperator::CreateOr(A, B);
2323
Chad Rosier7813dce2012-04-26 23:29:14 +00002324 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2325 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2326 return BinaryOperator::CreateOr(A, B);
2327
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002328 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2329 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2330 return BinaryOperator::CreateOr(Not, Op0);
2331 }
2332 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2333 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2334 return BinaryOperator::CreateOr(Not, Op0);
2335 }
2336 }
2337
2338 // A | ~(A | B) -> A | ~B
2339 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002340 if (match(Op1, m_Not(m_Value(A))))
2341 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002342 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2343 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2344 B->getOpcode() == Instruction::Xor)) {
2345 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2346 B->getOperand(0);
2347 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2348 return BinaryOperator::CreateOr(Not, Op0);
2349 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002350
Suyog Sarda16d64652014-08-01 04:41:43 +00002351 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2352 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2353 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2354 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2355
2356 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2357 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2358 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2359 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2360
Eli Friedmane06535b2012-03-16 00:52:42 +00002361 if (SwappedForXor)
2362 std::swap(Op0, Op1);
2363
David Majnemer3d6f80b2014-11-28 19:58:29 +00002364 {
2365 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2366 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2367 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002368 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002369 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002370
David Majnemer3d6f80b2014-11-28 19:58:29 +00002371 // TODO: Make this recursive; it's a little tricky because an arbitrary
2372 // number of 'or' instructions might have to be created.
2373 Value *X, *Y;
2374 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2375 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2376 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002377 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002378 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2379 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002380 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002381 }
2382 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2383 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2384 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002385 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002386 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2387 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002389 }
2390 }
2391
Chris Lattner4e8137d2010-02-11 06:26:33 +00002392 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2393 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2394 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002395 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002396 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002397
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002398 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2399 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002400
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002401 // 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 +00002402 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002403 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002404 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002405 if (match(Op1, 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), Op0);
2408
Owen Andersonc237a842010-09-13 17:59:27 +00002409 // Note: If we've gotten to the point of visiting the outer OR, then the
2410 // inner one couldn't be simplified. If it was a constant, then it won't
2411 // be simplified by a later pass either, so we try swapping the inner/outer
2412 // ORs in the hopes that we'll be able to simplify it this way.
2413 // (X|C) | V --> (X|V) | C
2414 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2415 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2416 Value *Inner = Builder->CreateOr(A, Op1);
2417 Inner->takeName(Op0);
2418 return BinaryOperator::CreateOr(Inner, C1);
2419 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002420
Bill Wendling23242092013-02-16 23:41:36 +00002421 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2422 // Since this OR statement hasn't been optimized further yet, we hope
2423 // that this transformation will allow the new ORs to be optimized.
2424 {
Craig Topperf40110f2014-04-25 05:29:35 +00002425 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002426 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2427 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2428 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2429 Value *orTrue = Builder->CreateOr(A, C);
2430 Value *orFalse = Builder->CreateOr(B, D);
2431 return SelectInst::Create(X, orTrue, orFalse);
2432 }
2433 }
2434
Craig Topperf40110f2014-04-25 05:29:35 +00002435 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002436}
2437
2438Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002439 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2441
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002442 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002443 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002444
Chandler Carruth66b31302015-01-04 12:03:27 +00002445 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002446 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002447
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002448 // (A&B)^(A&C) -> A&(B^C) etc
2449 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002450 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002451
Craig Topper9d4171a2012-12-20 07:09:41 +00002452 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453 // purpose is to compute bits we don't care about.
2454 if (SimplifyDemandedInstructionBits(I))
2455 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002457 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002458 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002459
Chris Lattner0a8191e2010-01-05 07:50:36 +00002460 // Is this a ~ operation?
2461 if (Value *NotOp = dyn_castNotVal(&I)) {
2462 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002463 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002464 Op0I->getOpcode() == Instruction::Or) {
2465 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2466 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2467 if (dyn_castNotVal(Op0I->getOperand(1)))
2468 Op0I->swapOperands();
2469 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2470 Value *NotY =
2471 Builder->CreateNot(Op0I->getOperand(1),
2472 Op0I->getOperand(1)->getName()+".not");
2473 if (Op0I->getOpcode() == Instruction::And)
2474 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2475 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2476 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002477
Chris Lattner0a8191e2010-01-05 07:50:36 +00002478 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2479 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002480 if (IsFreeToInvert(Op0I->getOperand(0),
2481 Op0I->getOperand(0)->hasOneUse()) &&
2482 IsFreeToInvert(Op0I->getOperand(1),
2483 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002484 Value *NotX =
2485 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2486 Value *NotY =
2487 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2488 if (Op0I->getOpcode() == Instruction::And)
2489 return BinaryOperator::CreateOr(NotX, NotY);
2490 return BinaryOperator::CreateAnd(NotX, NotY);
2491 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002492
2493 } else if (Op0I->getOpcode() == Instruction::AShr) {
2494 // ~(~X >>s Y) --> (X >>s Y)
2495 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2496 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002497 }
2498 }
2499 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002500
Benjamin Kramer443c7962015-02-12 20:26:46 +00002501 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2502 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002504 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2505 return CmpInst::Create(CI->getOpcode(),
2506 CI->getInversePredicate(),
2507 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002508 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509
Benjamin Kramer443c7962015-02-12 20:26:46 +00002510 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002511 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2512 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2513 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2514 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2515 Instruction::CastOps Opcode = Op0C->getOpcode();
2516 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002517 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002518 Op0C->getDestTy()))) {
2519 CI->setPredicate(CI->getInversePredicate());
2520 return CastInst::Create(Opcode, CI, Op0C->getType());
2521 }
2522 }
2523 }
2524 }
2525
2526 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2527 // ~(c-X) == X-c-1 == X+(-c-1)
2528 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2529 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2530 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2531 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2532 ConstantInt::get(I.getType(), 1));
2533 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2534 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002535
Chris Lattner0a8191e2010-01-05 07:50:36 +00002536 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2537 if (Op0I->getOpcode() == Instruction::Add) {
2538 // ~(X-c) --> (-c-1)-X
2539 if (RHS->isAllOnesValue()) {
2540 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2541 return BinaryOperator::CreateSub(
2542 ConstantExpr::getSub(NegOp0CI,
2543 ConstantInt::get(I.getType(), 1)),
2544 Op0I->getOperand(0));
2545 } else if (RHS->getValue().isSignBit()) {
2546 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002547 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002548 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2549
2550 }
2551 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002552 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002553 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2554 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002555 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2556 // Anything in both C1 and C2 is known to be zero, remove it from
2557 // NewRHS.
2558 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002559 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002560 ConstantExpr::getNot(CommonBits));
2561 Worklist.Add(Op0I);
2562 I.setOperand(0, Op0I->getOperand(0));
2563 I.setOperand(1, NewRHS);
2564 return &I;
2565 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002566 } else if (Op0I->getOpcode() == Instruction::LShr) {
2567 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2568 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002569 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002570 ConstantInt *C1;
2571 if (Op0I->hasOneUse() &&
2572 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2573 E1->getOpcode() == Instruction::Xor &&
2574 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2575 // fold (C1 >> C2) ^ C3
2576 ConstantInt *C2 = Op0CI, *C3 = RHS;
2577 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2578 FoldConst ^= C3->getValue();
2579 // Prepare the two operands.
2580 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2581 Opnd0->takeName(Op0I);
2582 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2583 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2584
2585 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2586 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587 }
2588 }
2589 }
2590
2591 // Try to fold constant and into select arguments.
2592 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2593 if (Instruction *R = FoldOpIntoSelect(I, SI))
2594 return R;
2595 if (isa<PHINode>(Op0))
2596 if (Instruction *NV = FoldOpIntoPhi(I))
2597 return NV;
2598 }
2599
Chris Lattner0a8191e2010-01-05 07:50:36 +00002600 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2601 if (Op1I) {
2602 Value *A, *B;
2603 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2604 if (A == Op0) { // B^(B|A) == (A|B)^B
2605 Op1I->swapOperands();
2606 I.swapOperands();
2607 std::swap(Op0, Op1);
2608 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2609 I.swapOperands(); // Simplified below.
2610 std::swap(Op0, Op1);
2611 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002612 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002613 Op1I->hasOneUse()){
2614 if (A == Op0) { // A^(A&B) -> A^(B&A)
2615 Op1I->swapOperands();
2616 std::swap(A, B);
2617 }
2618 if (B == Op0) { // A^(B&A) -> (B&A)^A
2619 I.swapOperands(); // Simplified below.
2620 std::swap(Op0, Op1);
2621 }
2622 }
2623 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002624
Chris Lattner0a8191e2010-01-05 07:50:36 +00002625 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2626 if (Op0I) {
2627 Value *A, *B;
2628 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2629 Op0I->hasOneUse()) {
2630 if (A == Op1) // (B|A)^B == (A|B)^B
2631 std::swap(A, B);
2632 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002633 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002634 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002635 Op0I->hasOneUse()){
2636 if (A == Op1) // (A&B)^A -> (B&A)^A
2637 std::swap(A, B);
2638 if (B == Op1 && // (B&A)^A == ~B & A
2639 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002640 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002641 }
2642 }
2643 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002644
Chris Lattner0a8191e2010-01-05 07:50:36 +00002645 if (Op0I && Op1I) {
2646 Value *A, *B, *C, *D;
2647 // (A & B)^(A | B) -> A ^ B
2648 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2649 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002650 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002651 return BinaryOperator::CreateXor(A, B);
2652 }
2653 // (A | B)^(A & B) -> A ^ B
2654 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2655 match(Op1I, m_And(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 }
David Majnemer698dca02014-08-14 06:46:25 +00002659 // (A | ~B) ^ (~A | B) -> A ^ B
2660 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2661 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2662 return BinaryOperator::CreateXor(A, B);
2663 }
2664 // (~A | B) ^ (A | ~B) -> A ^ B
2665 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2666 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2667 return BinaryOperator::CreateXor(A, B);
2668 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002669 // (A & ~B) ^ (~A & B) -> A ^ B
2670 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2671 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2672 return BinaryOperator::CreateXor(A, B);
2673 }
2674 // (~A & B) ^ (A & ~B) -> A ^ B
2675 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2676 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2677 return BinaryOperator::CreateXor(A, B);
2678 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002679 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2680 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2681 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2682 if (D == A)
2683 return BinaryOperator::CreateXor(
2684 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2685 if (D == B)
2686 return BinaryOperator::CreateXor(
2687 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002688 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002689 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002690 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002691 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2692 if (D == A)
2693 return BinaryOperator::CreateXor(
2694 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2695 if (D == B)
2696 return BinaryOperator::CreateXor(
2697 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002698 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002699 // (A & B) ^ (A ^ B) -> (A | B)
2700 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2701 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2702 return BinaryOperator::CreateOr(A, B);
2703 // (A ^ B) ^ (A & B) -> (A | B)
2704 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2705 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2706 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002707 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002708
Suyog Sarda521237c2014-07-22 15:37:39 +00002709 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002710 // (A & ~B) ^ (~A) -> ~(A & B)
2711 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2712 match(Op1, m_Not(m_Specific(A))))
2713 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2714
Chris Lattner0a8191e2010-01-05 07:50:36 +00002715 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2716 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2717 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2718 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2719 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2720 LHS->getOperand(1) == RHS->getOperand(0))
2721 LHS->swapOperands();
2722 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2723 LHS->getOperand(1) == RHS->getOperand(1)) {
2724 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2725 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2726 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002727 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002728 getNewICmpValue(isSigned, Code, Op0, Op1,
2729 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002730 }
2731 }
2732
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002733 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2734 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002735
Craig Topperf40110f2014-04-25 05:29:35 +00002736 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002737}