blob: fa2631c953511cdcda3685f7de5fa2947cb3f520 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Chris Lattner0a8191e2010-01-05 07:50:36 +000026static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000031 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 return Operand;
33 }
Craig Topper9d4171a2012-12-20 07:09:41 +000034
Chris Lattner0a8191e2010-01-05 07:50:36 +000035 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000039}
40
Sanjay Patel18549272015-09-08 18:24:36 +000041/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000042/// a four bit mask.
43static unsigned getFCmpCode(FCmpInst::Predicate CC) {
44 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
45 "Unexpected FCmp predicate!");
46 // Take advantage of the bit pattern of FCmpInst::Predicate here.
47 // U L G E
48 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
49 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
50 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
51 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
52 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
53 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
54 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
55 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
56 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
57 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
58 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
59 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
60 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
61 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
62 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
63 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
64 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000065}
66
Sanjay Patel18549272015-09-08 18:24:36 +000067/// This is the complement of getICmpCode, which turns an opcode and two
68/// operands into either a constant true or false, or a brand new ICmp
69/// instruction. The sign is passed in to determine which kind of predicate to
70/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000071static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000073 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75 return NewConstant;
76 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000077}
78
Sanjay Patel18549272015-09-08 18:24:36 +000079/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000080/// operands into either a FCmp instruction, or a true/false constant.
81static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Chris Lattner067459c2010-03-05 08:46:26 +000082 InstCombiner::BuilderTy *Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000083 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
84 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
85 "Unexpected FCmp predicate!");
86 if (Pred == FCmpInst::FCMP_FALSE)
87 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
88 if (Pred == FCmpInst::FCMP_TRUE)
89 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner067459c2010-03-05 08:46:26 +000090 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000091}
92
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000093/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
94/// \param I Binary operator to transform.
95/// \return Pointer to node that must replace the original binary operator, or
96/// null pointer if no transformation was made.
97Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
98 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
99
100 // Can't do vectors.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000101 if (I.getType()->isVectorTy())
102 return nullptr;
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000103
104 // Can only do bitwise ops.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000105 if (!I.isBitwiseLogicOp())
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000106 return nullptr;
107
108 Value *OldLHS = I.getOperand(0);
109 Value *OldRHS = I.getOperand(1);
110 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
111 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
112 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
113 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
114 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
115 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
116
117 if (!IsBswapLHS && !IsBswapRHS)
118 return nullptr;
119
120 if (!IsBswapLHS && !ConstLHS)
121 return nullptr;
122
123 if (!IsBswapRHS && !ConstRHS)
124 return nullptr;
125
126 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
127 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
128 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
129 Builder->getInt(ConstLHS->getValue().byteSwap());
130
131 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
132 Builder->getInt(ConstRHS->getValue().byteSwap());
133
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000134 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000135 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000136 return Builder->CreateCall(F, BinOp);
137}
138
Sanjay Patel18549272015-09-08 18:24:36 +0000139/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000140/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
141Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142 ConstantInt *OpRHS,
143 ConstantInt *AndRHS,
144 BinaryOperator &TheAnd) {
145 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000146 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000147 if (!Op->isShift())
148 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
149
150 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000151 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000152 case Instruction::Xor:
153 if (Op->hasOneUse()) {
154 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
155 Value *And = Builder->CreateAnd(X, AndRHS);
156 And->takeName(Op);
157 return BinaryOperator::CreateXor(And, Together);
158 }
159 break;
160 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000161 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000162 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
163 if (TogetherCI && !TogetherCI->isZero()){
164 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
165 // NOTE: This reduces the number of bits set in the & mask, which
166 // can expose opportunities for store narrowing.
167 Together = ConstantExpr::getXor(AndRHS, Together);
168 Value *And = Builder->CreateAnd(X, Together);
169 And->takeName(Op);
170 return BinaryOperator::CreateOr(And, OpRHS);
171 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000172 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000173
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174 break;
175 case Instruction::Add:
176 if (Op->hasOneUse()) {
177 // Adding a one to a single bit bit-field should be turned into an XOR
178 // of the bit. First thing to check is to see if this AND is with a
179 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000180 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181
182 // If there is only one bit set.
183 if (AndRHSV.isPowerOf2()) {
184 // Ok, at this point, we know that we are masking the result of the
185 // ADD down to exactly one bit. If the constant we are adding has
186 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000187 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000188
189 // Check to see if any bits below the one bit set in AndRHSV are set.
190 if ((AddRHS & (AndRHSV-1)) == 0) {
191 // If not, the only thing that can effect the output of the AND is
192 // the bit specified by AndRHSV. If that bit is set, the effect of
193 // the XOR is to toggle the bit. If it is clear, then the ADD has
194 // no effect.
195 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
196 TheAnd.setOperand(0, X);
197 return &TheAnd;
198 } else {
199 // Pull the XOR out of the AND.
200 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
201 NewAnd->takeName(Op);
202 return BinaryOperator::CreateXor(NewAnd, AndRHS);
203 }
204 }
205 }
206 }
207 break;
208
209 case Instruction::Shl: {
210 // We know that the AND will not produce any of the bits shifted in, so if
211 // the anded constant includes them, clear them now!
212 //
213 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
214 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
215 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000216 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000217
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000218 if (CI->getValue() == ShlMask)
219 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000220 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000221
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000222 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000223 TheAnd.setOperand(1, CI);
224 return &TheAnd;
225 }
226 break;
227 }
228 case Instruction::LShr: {
229 // We know that the AND will not produce any of the bits shifted in, so if
230 // the anded constant includes them, clear them now! This only applies to
231 // unsigned shifts, because a signed shr may bring in set bits!
232 //
233 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
234 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
235 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000236 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000237
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000238 if (CI->getValue() == ShrMask)
239 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000240 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000241
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000242 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
244 return &TheAnd;
245 }
246 break;
247 }
248 case Instruction::AShr:
249 // Signed shr.
250 // See if this is shifting in some sign extension, then masking it out
251 // with an and.
252 if (Op->hasOneUse()) {
253 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
254 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
255 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000256 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000257 if (C == AndRHS) { // Masking out bits shifted in.
258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
259 // Make the argument unsigned.
260 Value *ShVal = Op->getOperand(0);
261 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
262 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
263 }
264 }
265 break;
266 }
Craig Topperf40110f2014-04-25 05:29:35 +0000267 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000268}
269
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000271/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
272/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000273Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000274 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000275 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000276 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000277
Sanjay Patel85d79742016-08-31 19:49:56 +0000278 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000279 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000280 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000281
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000282 // V >= Min && V < Hi --> V < Hi
283 // V < Min || V >= Hi --> V >= Hi
284 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000285 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000286 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000287 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000288 }
289
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000290 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
291 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000292 Value *VMinusLo =
293 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
294 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000295 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000296}
297
Sanjay Patel77bf6222017-04-03 16:53:12 +0000298/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
299/// that can be simplified.
300/// One of A and B is considered the mask. The other is the value. This is
301/// described as the "AMask" or "BMask" part of the enum. If the enum contains
302/// only "Mask", then both A and B can be considered masks. If A is the mask,
303/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
304/// If both A and C are constants, this proof is also easy.
305/// For the following explanations, we assume that A is the mask.
306///
307/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
308/// bits of A are set in B.
309/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
310///
311/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
312/// bits of A are cleared in B.
313/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
314///
315/// "Mixed" declares that (A & B) == C and C might or might not contain any
316/// number of one bits and zero bits.
317/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
318///
319/// "Not" means that in above descriptions "==" should be replaced by "!=".
320/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
321///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000322/// If the mask A contains a single bit, then the following is equivalent:
323/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
324/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
325enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000326 AMask_AllOnes = 1,
327 AMask_NotAllOnes = 2,
328 BMask_AllOnes = 4,
329 BMask_NotAllOnes = 8,
330 Mask_AllZeros = 16,
331 Mask_NotAllZeros = 32,
332 AMask_Mixed = 64,
333 AMask_NotMixed = 128,
334 BMask_Mixed = 256,
335 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000336};
337
Sanjay Patel77bf6222017-04-03 16:53:12 +0000338/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
339/// satisfies.
340static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
341 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000342 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
343 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
344 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000345 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
346 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
347 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
348 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000349 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000350 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000351 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
352 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
353 if (IsAPow2)
354 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
355 : (AMask_AllOnes | AMask_Mixed));
356 if (IsBPow2)
357 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
358 : (BMask_AllOnes | BMask_Mixed));
359 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000360 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000361
Owen Anderson3fe002d2010-09-08 22:16:17 +0000362 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000363 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
364 : (AMask_NotAllOnes | AMask_NotMixed));
365 if (IsAPow2)
366 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
367 : (Mask_AllZeros | AMask_Mixed));
368 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
369 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000370 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000371
Craig Topperae48cb22012-12-20 07:15:54 +0000372 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000373 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
374 : (BMask_NotAllOnes | BMask_NotMixed));
375 if (IsBPow2)
376 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
377 : (Mask_AllZeros | BMask_Mixed));
378 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
379 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000380 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000381
382 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000383}
384
Tim Northoverc0756c42013-09-04 11:57:13 +0000385/// Convert an analysis of a masked ICmp into its equivalent if all boolean
386/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
387/// is adjacent to the corresponding normal flag (recording ==), this just
388/// involves swapping those bits over.
389static unsigned conjugateICmpMask(unsigned Mask) {
390 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000391 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
392 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000393 << 1;
394
Sanjay Patel77bf6222017-04-03 16:53:12 +0000395 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
396 AMask_NotMixed | BMask_NotMixed))
397 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000398
399 return NewMask;
400}
401
Sanjay Patel77bf6222017-04-03 16:53:12 +0000402/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
403/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
404/// RHS satisfy.
405static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
406 Value *&D, Value *&E, ICmpInst *LHS,
407 ICmpInst *RHS,
408 ICmpInst::Predicate &PredL,
409 ICmpInst::Predicate &PredR) {
410 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
411 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000412 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000413 if (LHS->getOperand(0)->getType()->isVectorTy())
414 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415
416 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000417 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000418 // and L11 & L12 == L21 & L22. The same goes for RHS.
419 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000420 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000421 // above.
422 Value *L1 = LHS->getOperand(0);
423 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000424 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000425 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000426 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000427 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000428 } else {
429 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000430 if (!L1->getType()->isIntegerTy()) {
431 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000432 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000433 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
434 // Any icmp can be viewed as being trivially masked; if it allows us to
435 // remove one, it's worth it.
436 L11 = L1;
437 L12 = Constant::getAllOnesValue(L1->getType());
438 }
439
440 if (!L2->getType()->isIntegerTy()) {
441 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000442 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000443 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
444 L21 = L2;
445 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000446 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000447 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000448
449 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000450 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000451 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000452
453 Value *R1 = RHS->getOperand(0);
454 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000455 Value *R11, *R12;
456 bool Ok = false;
457 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000458 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000459 A = R11;
460 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000461 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000462 A = R12;
463 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000464 } else {
465 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000467 E = R2;
468 R1 = nullptr;
469 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000470 } else if (R1->getType()->isIntegerTy()) {
471 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
472 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000473 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000474 R11 = R1;
475 R12 = Constant::getAllOnesValue(R1->getType());
476 }
477
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000478 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000479 A = R11;
480 D = R12;
481 E = R2;
482 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000483 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000484 A = R12;
485 D = R11;
486 E = R2;
487 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000488 }
489 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000490
491 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000492 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000493 return 0;
494
Chad Rosier58919cc2016-05-09 21:37:43 +0000495 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000496 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000497 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
498 R11 = R2;
499 R12 = Constant::getAllOnesValue(R2->getType());
500 }
501
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000502 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000503 A = R11;
504 D = R12;
505 E = R1;
506 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000507 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000508 A = R12;
509 D = R11;
510 E = R1;
511 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000512 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000513 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000514 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000515 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000516 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000517 return 0;
518
519 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000520 B = L12;
521 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000522 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000523 B = L11;
524 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000525 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000526 B = L22;
527 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000528 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000529 B = L21;
530 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000531 }
532
Sanjay Patel77bf6222017-04-03 16:53:12 +0000533 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
534 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000535 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000536}
Sanjay Patel18549272015-09-08 18:24:36 +0000537
538/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
539/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000540static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
541 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000542 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000543 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
544 unsigned Mask =
545 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
546 if (Mask == 0)
547 return nullptr;
548
549 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
550 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000551
Tim Northoverc0756c42013-09-04 11:57:13 +0000552 // In full generality:
553 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
554 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
555 //
556 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
557 // equivalent to (icmp (A & X) !Op Y).
558 //
559 // Therefore, we can pretend for the rest of this function that we're dealing
560 // with the conjunction, provided we flip the sense of any comparisons (both
561 // input and output).
562
563 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000564 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000565 if (!IsAnd) {
566 // Convert the masking analysis into its equivalent with negated
567 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000568 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000569 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000570
Sanjay Patel77bf6222017-04-03 16:53:12 +0000571 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000572 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000573 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000574 Value *NewOr = Builder->CreateOr(B, D);
575 Value *NewAnd = Builder->CreateAnd(A, NewOr);
576 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000577 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000578 // with B and D, having a single bit set.
579 Value *Zero = Constant::getNullValue(A->getType());
580 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000581 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000582 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000583 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000584 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000585 Value *NewOr = Builder->CreateOr(B, D);
586 Value *NewAnd = Builder->CreateAnd(A, NewOr);
587 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000588 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000589 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000590 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000591 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000592 Value *NewAnd1 = Builder->CreateAnd(B, D);
593 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
594 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000595 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000596
597 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000598 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000599 // easy cases for now" decision.
600 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000601 if (!BCst)
602 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000603 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000604 if (!DCst)
605 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000606
Sanjay Patel77bf6222017-04-03 16:53:12 +0000607 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000608 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
609 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
610 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
611 // Only valid if one of the masks is a superset of the other (check "B&D" is
612 // the same as either B or D).
613 APInt NewMask = BCst->getValue() & DCst->getValue();
614
615 if (NewMask == BCst->getValue())
616 return LHS;
617 else if (NewMask == DCst->getValue())
618 return RHS;
619 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000620
621 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000622 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
623 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
624 // Only valid if one of the masks is a superset of the other (check "B|D" is
625 // the same as either B or D).
626 APInt NewMask = BCst->getValue() | DCst->getValue();
627
628 if (NewMask == BCst->getValue())
629 return LHS;
630 else if (NewMask == DCst->getValue())
631 return RHS;
632 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000633
634 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000635 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000636 // We already know that B & C == C && D & E == E.
637 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
638 // C and E, which are shared by both the mask B and the mask D, don't
639 // contradict, then we can transform to
640 // -> (icmp eq (A & (B|D)), (C|E))
641 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000642 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000643 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000644 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000645 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000646 if (!CCst)
647 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000648 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000649 if (!ECst)
650 return nullptr;
651 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000652 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000653 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000654 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000655
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000656 // If there is a conflict, we should actually return a false for the
657 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000658 if (((BCst->getValue() & DCst->getValue()) &
659 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000660 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000661
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000662 Value *NewOr1 = Builder->CreateOr(B, D);
663 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
664 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
665 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000666 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000667
Craig Topperf40110f2014-04-25 05:29:35 +0000668 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000669}
670
Erik Ecksteind1817522014-12-03 10:39:15 +0000671/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
672/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
673/// If \p Inverted is true then the check is for the inverted range, e.g.
674/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
675Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
676 bool Inverted) {
677 // Check the lower range comparison, e.g. x >= 0
678 // InstCombine already ensured that if there is a constant it's on the RHS.
679 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
680 if (!RangeStart)
681 return nullptr;
682
683 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
684 Cmp0->getPredicate());
685
686 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
687 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
688 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
689 return nullptr;
690
691 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
692 Cmp1->getPredicate());
693
694 Value *Input = Cmp0->getOperand(0);
695 Value *RangeEnd;
696 if (Cmp1->getOperand(0) == Input) {
697 // For the upper range compare we have: icmp x, n
698 RangeEnd = Cmp1->getOperand(1);
699 } else if (Cmp1->getOperand(1) == Input) {
700 // For the upper range compare we have: icmp n, x
701 RangeEnd = Cmp1->getOperand(0);
702 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
703 } else {
704 return nullptr;
705 }
706
707 // Check the upper range comparison, e.g. x < n
708 ICmpInst::Predicate NewPred;
709 switch (Pred1) {
710 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
711 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
712 default: return nullptr;
713 }
714
715 // This simplification is only valid if the upper range is not negative.
716 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000717 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000718 if (!IsNotNegative)
719 return nullptr;
720
721 if (Inverted)
722 NewPred = ICmpInst::getInversePredicate(NewPred);
723
724 return Builder->CreateICmp(NewPred, Input, RangeEnd);
725}
726
Sanjay Patel18549272015-09-08 18:24:36 +0000727/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000728Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000729 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000730
731 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000732 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000733 if (LHS->getOperand(0) == RHS->getOperand(1) &&
734 LHS->getOperand(1) == RHS->getOperand(0))
735 LHS->swapOperands();
736 if (LHS->getOperand(0) == RHS->getOperand(0) &&
737 LHS->getOperand(1) == RHS->getOperand(1)) {
738 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
739 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
740 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000741 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000742 }
743 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000744
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000745 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000746 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000747 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000748
Erik Ecksteind1817522014-12-03 10:39:15 +0000749 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
750 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
751 return V;
752
753 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
754 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
755 return V;
756
Chris Lattner0a8191e2010-01-05 07:50:36 +0000757 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
758 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000759 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
760 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
761 if (!LHSC || !RHSC)
762 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000763
Sanjay Patel519a87a2017-04-05 17:38:34 +0000764 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000765 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000766 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000767 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000768 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
769 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000770 Value *NewOr = Builder->CreateOr(Val, Val2);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000771 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000772 }
773 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000774
Benjamin Kramer101720f2011-04-28 20:09:57 +0000775 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000776 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000777 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000778 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
779 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000780 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000781 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000782
783 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000784 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000785 if (match(Val2, m_Trunc(m_Value(V))) &&
Sanjay Patel519a87a2017-04-05 17:38:34 +0000786 match(Val, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
787 SmallC = RHSC;
788 BigC = LHSC;
Craig Topperae48cb22012-12-20 07:15:54 +0000789 } else if (match(Val, m_Trunc(m_Value(V))) &&
Sanjay Patel519a87a2017-04-05 17:38:34 +0000790 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
791 SmallC = LHSC;
792 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000793 }
794
Sanjay Patel519a87a2017-04-05 17:38:34 +0000795 if (SmallC && BigC) {
796 unsigned BigBitSize = BigC->getType()->getBitWidth();
797 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000798
799 // Check that the low bits are zero.
800 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000801 if ((Low & AndC->getValue()) == 0 && (Low & BigC->getValue()) == 0) {
802 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
803 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
804 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
805 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000806 }
807 }
808 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000809
Chris Lattner0a8191e2010-01-05 07:50:36 +0000810 // From here on, we only handle:
811 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000812 if (Val != Val2)
813 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000814
Sanjay Patel519a87a2017-04-05 17:38:34 +0000815 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
816 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
817 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
818 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
819 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000820 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000821
Chris Lattner0a8191e2010-01-05 07:50:36 +0000822 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000823 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000824 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000825
Chris Lattner0a8191e2010-01-05 07:50:36 +0000826 // Ensure that the larger constant is on the RHS.
827 bool ShouldSwap;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000828 if (CmpInst::isSigned(PredL) ||
829 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
830 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 else
Sanjay Patel519a87a2017-04-05 17:38:34 +0000832 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000833
Chris Lattner0a8191e2010-01-05 07:50:36 +0000834 if (ShouldSwap) {
835 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000836 std::swap(LHSC, RHSC);
837 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000838 }
839
Dan Gohman4a618822010-02-10 16:03:48 +0000840 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000841 // comparing a value against two constants and and'ing the result
842 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000843 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
844 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000845 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000846 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000847
Sanjay Patel519a87a2017-04-05 17:38:34 +0000848 switch (PredL) {
849 default:
850 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000851 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000852 switch (PredR) {
853 default:
854 llvm_unreachable("Unknown integer condition code!");
855 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
856 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
857 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000858 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000859 }
860 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000861 switch (PredR) {
862 default:
863 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000864 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000865 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
866 return Builder->CreateICmpULT(Val, LHSC);
867 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
868 return insertRangeTest(Val, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000869 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000870 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000871 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000872 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
873 return Builder->CreateICmpSLT(Val, LHSC);
874 break; // (X != 13 & X s< 15) -> no change
875 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
876 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
877 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000878 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000879 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000880 // Special case to get the ordering right when the values wrap around
881 // zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000882 if (LHSC->getValue() == 0 && RHSC->getValue().isAllOnesValue())
883 std::swap(LHSC, RHSC);
884 if (LHSC == SubOne(RHSC)) { // (X != 13 & X != 14) -> X-13 >u 1
885 Constant *AddC = ConstantExpr::getNeg(LHSC);
886 Value *Add = Builder->CreateAdd(Val, AddC, Val->getName() + ".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000887 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
Sanjay Patel519a87a2017-04-05 17:38:34 +0000888 Val->getName() + ".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000889 }
Sanjay Patel519a87a2017-04-05 17:38:34 +0000890 break; // (X != 13 & X != 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000891 }
892 break;
893 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000894 switch (PredR) {
895 default:
896 llvm_unreachable("Unknown integer condition code!");
897 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
898 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000899 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000900 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
901 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000902 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 }
904 break;
905 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000906 switch (PredR) {
907 default:
908 llvm_unreachable("Unknown integer condition code!");
Sanjay Patel519a87a2017-04-05 17:38:34 +0000909 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
910 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000911 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000912 }
913 break;
914 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000915 switch (PredR) {
916 default:
917 llvm_unreachable("Unknown integer condition code!");
918 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
919 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000920 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000921 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000922 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
923 return Builder->CreateICmp(PredL, Val, RHSC);
924 break; // (X u> 13 & X != 15) -> no change
925 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
926 return insertRangeTest(Val, LHSC->getValue() + 1, RHSC->getValue(), false,
927 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000928 }
929 break;
930 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000931 switch (PredR) {
932 default:
933 llvm_unreachable("Unknown integer condition code!");
934 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
935 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000936 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000937 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000938 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
939 return Builder->CreateICmp(PredL, Val, RHSC);
940 break; // (X s> 13 & X != 15) -> no change
941 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
942 return insertRangeTest(Val, LHSC->getValue() + 1, RHSC->getValue(), true,
943 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000944 }
945 break;
946 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000947
Craig Topperf40110f2014-04-25 05:29:35 +0000948 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949}
950
Sanjay Patel18549272015-09-08 18:24:36 +0000951/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
952/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +0000953Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000954 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
955 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
956 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
957
958 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
959 // Swap RHS operands to match LHS.
960 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
961 std::swap(Op1LHS, Op1RHS);
962 }
963
964 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
965 // Suppose the relation between x and y is R, where R is one of
966 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
967 // testing the desired relations.
968 //
969 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
970 // bool(R & CC0) && bool(R & CC1)
971 // = bool((R & CC0) & (R & CC1))
972 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
973 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
974 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
975 Builder);
976
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
978 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +0000979 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000980 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +0000981
Chris Lattner0a8191e2010-01-05 07:50:36 +0000982 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
983 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
984 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
985 // If either of the constants are nans, then the whole thing returns
986 // false.
987 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000988 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +0000989 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000990 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000991
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 // Handle vector zeros. This occurs because the canonical form of
993 // "fcmp ord x,x" is "fcmp ord x, 0".
994 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
995 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000996 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +0000997 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000999
Craig Topperf40110f2014-04-25 05:29:35 +00001000 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001001}
1002
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001003/// Match De Morgan's Laws:
1004/// (~A & ~B) == (~(A | B))
1005/// (~A | ~B) == (~(A & B))
1006static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1007 InstCombiner::BuilderTy *Builder) {
1008 auto Opcode = I.getOpcode();
1009 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1010 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001011 // Flip the logic operation.
1012 if (Opcode == Instruction::And)
1013 Opcode = Instruction::Or;
1014 else
1015 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001016
1017 Value *Op0 = I.getOperand(0);
1018 Value *Op1 = I.getOperand(1);
1019 // TODO: Use pattern matchers instead of dyn_cast.
1020 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1021 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1022 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001023 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1024 I.getName() + ".demorgan");
1025 return BinaryOperator::CreateNot(LogicOp);
1026 }
1027
1028 return nullptr;
1029}
1030
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001031bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1032 Value *CastSrc = CI->getOperand(0);
1033
1034 // Noop casts and casts of constants should be eliminated trivially.
1035 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1036 return false;
1037
1038 // If this cast is paired with another cast that can be eliminated, we prefer
1039 // to have it eliminated.
1040 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1041 if (isEliminableCastPair(PrecedingCI, CI))
1042 return false;
1043
1044 // If this is a vector sext from a compare, then we don't want to break the
1045 // idiom where each element of the extended vector is either zero or all ones.
1046 if (CI->getOpcode() == Instruction::SExt &&
1047 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1048 return false;
1049
1050 return true;
1051}
1052
Sanjay Patel60312bc42016-09-12 00:16:23 +00001053/// Fold {and,or,xor} (cast X), C.
1054static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1055 InstCombiner::BuilderTy *Builder) {
1056 Constant *C;
1057 if (!match(Logic.getOperand(1), m_Constant(C)))
1058 return nullptr;
1059
1060 auto LogicOpc = Logic.getOpcode();
1061 Type *DestTy = Logic.getType();
1062 Type *SrcTy = Cast->getSrcTy();
1063
1064 // If the first operand is bitcast, move the logic operation ahead of the
1065 // bitcast (do the logic operation in the original type). This can eliminate
1066 // bitcasts and allow combines that would otherwise be impeded by the bitcast.
1067 Value *X;
1068 if (match(Cast, m_BitCast(m_Value(X)))) {
1069 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1070 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, NewConstant);
1071 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1072 }
1073
1074 // Similarly, move the logic operation ahead of a zext if the constant is
1075 // unchanged in the smaller source type. Performing the logic in a smaller
1076 // type may provide more information to later folds, and the smaller logic
1077 // instruction may be cheaper (particularly in the case of vectors).
1078 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1079 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1080 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1081 if (ZextTruncC == C) {
1082 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1083 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1084 return new ZExtInst(NewOp, DestTy);
1085 }
1086 }
1087
1088 return nullptr;
1089}
1090
1091/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001092Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001093 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001094 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001095
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001096 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001097 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001098 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001099 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001100
Sanjay Patel9bba7502016-03-03 19:19:04 +00001101 // This must be a cast from an integer or integer vector source type to allow
1102 // transformation of the logic operation to the source type.
1103 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001104 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001105 if (!SrcTy->isIntOrIntVectorTy())
1106 return nullptr;
1107
Sanjay Patel60312bc42016-09-12 00:16:23 +00001108 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1109 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001110
Sanjay Patel9bba7502016-03-03 19:19:04 +00001111 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1112 if (!Cast1)
1113 return nullptr;
1114
1115 // Both operands of the logic operation are casts. The casts must be of the
1116 // same type for reduction.
1117 auto CastOpcode = Cast0->getOpcode();
1118 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001119 return nullptr;
1120
1121 Value *Cast0Src = Cast0->getOperand(0);
1122 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001123
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001124 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001125 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001126 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1127 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001128 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001129 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001130
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001131 // For now, only 'and'/'or' have optimizations after this.
1132 if (LogicOpc == Instruction::Xor)
1133 return nullptr;
1134
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001135 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001136 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001137 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1138 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1139 if (ICmp0 && ICmp1) {
1140 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1141 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1142 if (Res)
1143 return CastInst::Create(CastOpcode, Res, DestTy);
1144 return nullptr;
1145 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001146
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001147 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001148 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001149 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1150 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1151 if (FCmp0 && FCmp1) {
1152 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1153 : FoldOrOfFCmps(FCmp0, FCmp1);
1154 if (Res)
1155 return CastInst::Create(CastOpcode, Res, DestTy);
1156 return nullptr;
1157 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001158
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001159 return nullptr;
1160}
1161
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001162static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1163 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1164
1165 // Canonicalize SExt or Not to the LHS
1166 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1167 std::swap(Op0, Op1);
1168 }
1169
1170 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1171 Value *X = nullptr;
1172 if (match(Op0, m_SExt(m_Value(X))) &&
1173 X->getType()->getScalarType()->isIntegerTy(1)) {
1174 Value *Zero = Constant::getNullValue(Op1->getType());
1175 return SelectInst::Create(X, Op1, Zero);
1176 }
1177
1178 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1179 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1180 X->getType()->getScalarType()->isIntegerTy(1)) {
1181 Value *Zero = Constant::getNullValue(Op0->getType());
1182 return SelectInst::Create(X, Zero, Op1);
1183 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001184
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001185 return nullptr;
1186}
1187
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001188// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1189// here. We should standardize that construct where it is needed or choose some
1190// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001191Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001192 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001193 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1194
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001195 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001196 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001197
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001198 if (Value *V = SimplifyAndInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001199 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001200
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001201 // (A|B)&(A|C) -> A|(B&C) etc
1202 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001203 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001204
Craig Topper9d4171a2012-12-20 07:09:41 +00001205 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001206 // purpose is to compute bits we don't care about.
1207 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001208 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001209
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001210 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001211 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001212
Chris Lattner0a8191e2010-01-05 07:50:36 +00001213 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1214 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001215
1216 // Optimize a variety of ((val OP C1) & C2) combinations...
1217 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1218 Value *Op0LHS = Op0I->getOperand(0);
1219 Value *Op0RHS = Op0I->getOperand(1);
1220 switch (Op0I->getOpcode()) {
1221 default: break;
1222 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001223 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001224 // If the mask is only needed on one incoming arm, push it up.
1225 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001226
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001227 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001228 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001229 // Not masking anything out for the LHS, move to RHS.
1230 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1231 Op0RHS->getName()+".masked");
1232 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1233 }
1234 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001235 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001236 // Not masking anything out for the RHS, move to LHS.
1237 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1238 Op0LHS->getName()+".masked");
1239 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1240 }
1241
1242 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001243 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001244 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001245 // -x & 1 -> x & 1
1246 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1247 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1248
Chris Lattner0a8191e2010-01-05 07:50:36 +00001249 break;
1250
1251 case Instruction::Shl:
1252 case Instruction::LShr:
1253 // (1 << x) & 1 --> zext(x == 0)
1254 // (1 >> x) & 1 --> zext(x == 0)
1255 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1256 Value *NewICmp =
1257 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1258 return new ZExtInst(NewICmp, I.getType());
1259 }
1260 break;
1261 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001262
David Majnemerde55c602017-01-17 18:08:06 +00001263 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1264 // of X and OP behaves well when given trunc(C1) and X.
1265 switch (Op0I->getOpcode()) {
1266 default:
1267 break;
1268 case Instruction::Xor:
1269 case Instruction::Or:
1270 case Instruction::Mul:
1271 case Instruction::Add:
1272 case Instruction::Sub:
1273 Value *X;
1274 ConstantInt *C1;
1275 if (match(Op0I, m_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1))) ||
1276 match(Op0I, m_BinOp(m_ConstantInt(C1), m_ZExt(m_Value(X))))) {
1277 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1278 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1279 Value *BinOp;
1280 if (isa<ZExtInst>(Op0LHS))
1281 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1282 else
1283 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1284 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1285 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1286 return new ZExtInst(And, I.getType());
1287 }
1288 }
1289 }
1290
Chris Lattner0a8191e2010-01-05 07:50:36 +00001291 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1292 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1293 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001294 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001295
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001296 // If this is an integer truncation, and if the source is an 'and' with
1297 // immediate, transform it. This frequently occurs for bitfield accesses.
1298 {
Craig Topperf40110f2014-04-25 05:29:35 +00001299 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001300 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1301 // Change: and (trunc (and X, YC) to T), C2
1302 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001303 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001304 // other simplifications.
1305 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1306 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1307 C3 = ConstantExpr::getAnd(C3, AndRHS);
1308 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001309 }
1310 }
Craig Topper86173602017-04-04 20:26:25 +00001311 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001312
Craig Topper86173602017-04-04 20:26:25 +00001313 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001314 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1315 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001316
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001317 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1318 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001319
Chris Lattner0a8191e2010-01-05 07:50:36 +00001320 {
Craig Topperf40110f2014-04-25 05:29:35 +00001321 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322 // (A|B) & ~(A&B) -> A^B
1323 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1324 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1325 ((A == C && B == D) || (A == D && B == C)))
1326 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001327
Chris Lattner0a8191e2010-01-05 07:50:36 +00001328 // ~(A&B) & (A|B) -> A^B
1329 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1330 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1331 ((A == C && B == D) || (A == D && B == C)))
1332 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001333
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001334 // A&(A^B) => A & ~B
1335 {
1336 Value *tmpOp0 = Op0;
1337 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001338 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001339 if (A == Op1 || B == Op1 ) {
1340 tmpOp1 = Op0;
1341 tmpOp0 = Op1;
1342 // Simplify below
1343 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001344 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001345
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001346 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001347 if (B == tmpOp0) {
1348 std::swap(A, B);
1349 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001350 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001351 // A is originally -1 (or a vector of -1 and undefs), then we enter
1352 // an endless loop. By checking that A is non-constant we ensure that
1353 // we will never get to the loop.
1354 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001355 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001356 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001357 }
1358
1359 // (A&((~A)|B)) -> A&B
1360 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1361 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1362 return BinaryOperator::CreateAnd(A, Op1);
1363 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1364 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1365 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001366
1367 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1368 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1369 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1370 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1371 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1372
1373 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1374 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1375 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1376 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1377 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001378
1379 // (A | B) & ((~A) ^ B) -> (A & B)
1380 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1381 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1382 return BinaryOperator::CreateAnd(A, B);
1383
1384 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001385 // ((~A) ^ B) & (B | A) -> (A & B)
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001386 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001387 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001388 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001389 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001390
David Majnemer5e96f1b2014-08-30 06:18:20 +00001391 {
1392 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1393 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1394 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001395 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001396 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001397
David Majnemer5e96f1b2014-08-30 06:18:20 +00001398 // TODO: Make this recursive; it's a little tricky because an arbitrary
1399 // number of 'and' instructions might have to be created.
1400 Value *X, *Y;
1401 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1402 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1403 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001404 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001405 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1406 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001407 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001408 }
1409 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1410 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1411 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001412 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001413 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1414 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001415 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001416 }
1417 }
1418
Chris Lattner4e8137d2010-02-11 06:26:33 +00001419 // If and'ing two fcmp, try combine them into one.
1420 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1421 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001422 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001423 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001424
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001425 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1426 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001427
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001428 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1429 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001430
Craig Topperf40110f2014-04-25 05:29:35 +00001431 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001432}
1433
Chad Rosiera00df492016-05-25 16:22:14 +00001434/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1435/// insert the new intrinsic and return it.
1436Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1438
1439 // Look through zero extends.
1440 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1441 Op0 = Ext->getOperand(0);
1442
1443 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1444 Op1 = Ext->getOperand(0);
1445
1446 // (A | B) | C and A | (B | C) -> bswap if possible.
1447 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1448 match(Op1, m_Or(m_Value(), m_Value()));
1449
1450 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1451 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1452 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1453
1454 // (A & B) | (C & D) -> bswap if possible.
1455 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1456 match(Op1, m_And(m_Value(), m_Value()));
1457
1458 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1459 return nullptr;
1460
James Molloyf01488e2016-01-15 09:20:19 +00001461 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001462 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001463 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001464 Instruction *LastInst = Insts.pop_back_val();
1465 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001466
James Molloyf01488e2016-01-15 09:20:19 +00001467 for (auto *Inst : Insts)
1468 Worklist.Add(Inst);
1469 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001470}
1471
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001472/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1473static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1474 unsigned NumElts = C1->getType()->getVectorNumElements();
1475 for (unsigned i = 0; i != NumElts; ++i) {
1476 Constant *EltC1 = C1->getAggregateElement(i);
1477 Constant *EltC2 = C2->getAggregateElement(i);
1478 if (!EltC1 || !EltC2)
1479 return false;
1480
1481 // One element must be all ones, and the other must be all zeros.
1482 // FIXME: Allow undef elements.
1483 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1484 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1485 return false;
1486 }
1487 return true;
1488}
1489
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001490/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1491/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1492/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001493static Value *getSelectCondition(Value *A, Value *B,
1494 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001495 // If these are scalars or vectors of i1, A can be used directly.
1496 Type *Ty = A->getType();
1497 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1498 return A;
1499
1500 // If A and B are sign-extended, look through the sexts to find the booleans.
1501 Value *Cond;
1502 if (match(A, m_SExt(m_Value(Cond))) &&
1503 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1504 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1505 m_SExt(m_Not(m_Specific(Cond))))))
1506 return Cond;
1507
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001508 // All scalar (and most vector) possibilities should be handled now.
1509 // Try more matches that only apply to non-splat constant vectors.
1510 if (!Ty->isVectorTy())
1511 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001512
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001513 // If both operands are constants, see if the constants are inverse bitmasks.
1514 Constant *AC, *BC;
1515 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1516 areInverseVectorBitmasks(AC, BC))
1517 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1518
1519 // If both operands are xor'd with constants using the same sexted boolean
1520 // operand, see if the constants are inverse bitmasks.
1521 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1522 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1523 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1524 areInverseVectorBitmasks(AC, BC)) {
1525 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1526 return Builder.CreateXor(Cond, AC);
1527 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001528 return nullptr;
1529}
1530
1531/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1532/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001533static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001534 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001535 // The potential condition of the select may be bitcasted. In that case, look
1536 // through its bitcast and the corresponding bitcast of the 'not' condition.
1537 Type *OrigType = A->getType();
1538 Value *SrcA, *SrcB;
Sanjay Patel664514f2016-07-08 21:17:51 +00001539 if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1540 match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001541 A = SrcA;
1542 B = SrcB;
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001543 }
1544
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001545 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001546 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001547 // The bitcasts will either all exist or all not exist. The builder will
1548 // not create unnecessary casts if the types already match.
1549 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1550 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1551 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1552 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001553 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001554
Craig Topperf40110f2014-04-25 05:29:35 +00001555 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001556}
1557
Sanjay Patel18549272015-09-08 18:24:36 +00001558/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001559Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1560 Instruction *CxtI) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001561 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001562
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001563 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1564 // if K1 and K2 are a one-bit mask.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001565 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1566 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001567
Sanjay Patel519a87a2017-04-05 17:38:34 +00001568 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero() &&
1569 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001570
1571 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1572 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1573 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1574 LAnd->getOpcode() == Instruction::And &&
1575 RAnd->getOpcode() == Instruction::And) {
1576
Craig Topperf40110f2014-04-25 05:29:35 +00001577 Value *Mask = nullptr;
1578 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001579 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001580 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001581 &DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001582 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001583 &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001584 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1585 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1586 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001587 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, &AC,
1588 CxtI, &DT) &&
1589 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, &AC,
1590 CxtI, &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001591 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1592 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1593 }
1594
1595 if (Masked)
1596 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1597 }
1598 }
1599
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001600 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1601 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1602 // The original condition actually refers to the following two ranges:
1603 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1604 // We can fold these two ranges if:
1605 // 1) C1 and C2 is unsigned greater than C3.
1606 // 2) The two ranges are separated.
1607 // 3) C1 ^ C2 is one-bit mask.
1608 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1609 // This implies all values in the two ranges differ by exactly one bit.
1610
Sanjay Patel519a87a2017-04-05 17:38:34 +00001611 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1612 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1613 LHSC->getType() == RHSC->getType() &&
1614 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001615
1616 Value *LAdd = LHS->getOperand(0);
1617 Value *RAdd = RHS->getOperand(0);
1618
1619 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001620 ConstantInt *LAddC, *RAddC;
1621 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1622 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1623 LAddC->getValue().ugt(LHSC->getValue()) &&
1624 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001625
Sanjay Patel519a87a2017-04-05 17:38:34 +00001626 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1627 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1628 ConstantInt *MaxAddC = nullptr;
1629 if (LAddC->getValue().ult(RAddC->getValue()))
1630 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001631 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001632 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001633
Sanjay Patel519a87a2017-04-05 17:38:34 +00001634 APInt RRangeLow = -RAddC->getValue();
1635 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1636 APInt LRangeLow = -LAddC->getValue();
1637 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001638 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1639 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1640 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1641 : RRangeLow - LRangeLow;
1642
1643 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001644 RangeDiff.ugt(LHSC->getValue())) {
1645 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001646
Sanjay Patel519a87a2017-04-05 17:38:34 +00001647 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1648 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1649 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001650 }
1651 }
1652 }
1653 }
1654
Chris Lattner0a8191e2010-01-05 07:50:36 +00001655 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001656 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001657 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1658 LHS->getOperand(1) == RHS->getOperand(0))
1659 LHS->swapOperands();
1660 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1661 LHS->getOperand(1) == RHS->getOperand(1)) {
1662 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1663 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1664 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001665 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001666 }
1667 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001668
1669 // handle (roughly):
1670 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001671 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001672 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001673
Chris Lattner0a8191e2010-01-05 07:50:36 +00001674 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001675 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1676 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1677 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001678 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001679 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
David Majnemerc2a990b2013-07-05 00:31:17 +00001680 B = Val;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001681 if (PredR == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
David Majnemerc2a990b2013-07-05 00:31:17 +00001682 A = Val2;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001683 else if (PredR == ICmpInst::ICMP_UGT && Val == Val2)
David Majnemerc2a990b2013-07-05 00:31:17 +00001684 A = RHS->getOperand(1);
1685 }
1686 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1687 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001688 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
David Majnemerc2a990b2013-07-05 00:31:17 +00001689 B = Val2;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001690 if (PredL == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
David Majnemerc2a990b2013-07-05 00:31:17 +00001691 A = Val;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001692 else if (PredL == ICmpInst::ICMP_UGT && Val2 == Val)
David Majnemerc2a990b2013-07-05 00:31:17 +00001693 A = LHS->getOperand(1);
1694 }
1695 if (A && B)
1696 return Builder->CreateICmp(
1697 ICmpInst::ICMP_UGE,
1698 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1699 }
1700
Erik Ecksteind1817522014-12-03 10:39:15 +00001701 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1702 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1703 return V;
1704
1705 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1706 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1707 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001708
David Majnemerc2a990b2013-07-05 00:31:17 +00001709 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001710 if (!LHSC || !RHSC)
1711 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001712
Sanjay Patel519a87a2017-04-05 17:38:34 +00001713 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001714 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001715 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001716 Value *NewOr = Builder->CreateOr(Val, Val2);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001717 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001718 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001719 }
1720
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001721 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001722 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001723 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1724 ConstantInt *AddC;
1725 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddC))))
1726 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
1727 return Builder->CreateICmpULE(Val, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001728 }
1729
Chris Lattner0a8191e2010-01-05 07:50:36 +00001730 // From here on, we only handle:
1731 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001732 if (Val != Val2)
1733 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001734
Sanjay Patel519a87a2017-04-05 17:38:34 +00001735 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1736 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1737 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1738 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1739 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001740 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001741
Chris Lattner0a8191e2010-01-05 07:50:36 +00001742 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001743 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001744 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001745
Chris Lattner0a8191e2010-01-05 07:50:36 +00001746 // Ensure that the larger constant is on the RHS.
1747 bool ShouldSwap;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001748 if (CmpInst::isSigned(PredL) ||
1749 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
1750 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001751 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001752 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001753
Chris Lattner0a8191e2010-01-05 07:50:36 +00001754 if (ShouldSwap) {
1755 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001756 std::swap(LHSC, RHSC);
1757 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001758 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001759
Dan Gohman4a618822010-02-10 16:03:48 +00001760 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001761 // comparing a value against two constants and or'ing the result
1762 // together. Because of the above check, we know that we only have
1763 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1764 // icmp folding check above), that the two constants are not
1765 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001766 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001767
Sanjay Patel519a87a2017-04-05 17:38:34 +00001768 switch (PredL) {
1769 default:
1770 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001771 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001772 switch (PredR) {
1773 default:
1774 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001775 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001776 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001777 // if LHSC and RHSC differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001778 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Sanjay Patel519a87a2017-04-05 17:38:34 +00001779 assert(LHSC->getValue().ule(LHSC->getValue()));
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001780
Sanjay Patel519a87a2017-04-05 17:38:34 +00001781 APInt Xor = LHSC->getValue() ^ RHSC->getValue();
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001782 if (Xor.isPowerOf2()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001783 Value *C = Builder->getInt(Xor);
1784 Value *Or = Builder->CreateOr(LHS->getOperand(0), C);
1785 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSC);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001786 }
1787 }
1788
Sanjay Patel519a87a2017-04-05 17:38:34 +00001789 if (LHSC == SubOne(RHSC)) {
David Majnemer1fae1952013-04-14 21:15:43 +00001790 // (X == 13 | X == 14) -> X-13 <u 2
Sanjay Patel519a87a2017-04-05 17:38:34 +00001791 Constant *AddC = ConstantExpr::getNeg(LHSC);
1792 Value *Add = Builder->CreateAdd(Val, AddC, Val->getName() + ".off");
1793 AddC = ConstantExpr::getSub(AddOne(RHSC), LHSC);
1794 return Builder->CreateICmpULT(Add, AddC);
David Majnemer1fae1952013-04-14 21:15:43 +00001795 }
1796
Sanjay Patel519a87a2017-04-05 17:38:34 +00001797 break; // (X == 13 | X == 15) -> no change
1798 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1799 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001800 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001801 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1802 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1803 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001804 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805 }
1806 break;
1807 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001808 switch (PredR) {
1809 default:
1810 llvm_unreachable("Unknown integer condition code!");
1811 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1812 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1813 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001814 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001815 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1816 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1817 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001818 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001820 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001821 switch (PredR) {
1822 default:
1823 llvm_unreachable("Unknown integer condition code!");
1824 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001825 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001826 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1827 // If RHSC is [us]MAXINT, it is always false. Not handling
Chris Lattner0a8191e2010-01-05 07:50:36 +00001828 // this can cause overflow.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001829 if (RHSC->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001830 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001831 return insertRangeTest(Val, LHSC->getValue(), RHSC->getValue() + 1, false,
1832 false);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001833 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1834 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001835 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836 }
1837 break;
1838 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001839 switch (PredR) {
1840 default:
1841 llvm_unreachable("Unknown integer condition code!");
1842 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001843 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001844 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1845 // If RHSC is [us]MAXINT, it is always false. Not handling
Chris Lattner0a8191e2010-01-05 07:50:36 +00001846 // this can cause overflow.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001847 if (RHSC->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001848 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001849 return insertRangeTest(Val, LHSC->getValue(), RHSC->getValue() + 1, true,
1850 false);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001851 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1852 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001853 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001854 }
1855 break;
1856 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001857 switch (PredR) {
1858 default:
1859 llvm_unreachable("Unknown integer condition code!");
1860 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1861 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001862 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001863 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1864 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001865 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001866 }
1867 break;
1868 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001869 switch (PredR) {
1870 default:
1871 llvm_unreachable("Unknown integer condition code!");
1872 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1873 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001874 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001875 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1876 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001877 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001878 }
1879 break;
1880 }
Craig Topperf40110f2014-04-25 05:29:35 +00001881 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001882}
1883
Sanjay Patel18549272015-09-08 18:24:36 +00001884/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1885/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001886Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001887 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1888 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1889 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1890
1891 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1892 // Swap RHS operands to match LHS.
1893 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1894 std::swap(Op1LHS, Op1RHS);
1895 }
1896
1897 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1898 // This is a similar transformation to the one in FoldAndOfFCmps.
1899 //
1900 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1901 // bool(R & CC0) || bool(R & CC1)
1902 // = bool((R & CC0) | (R & CC1))
1903 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1904 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1905 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1906 Builder);
1907
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001909 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1911 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1912 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1913 // If either of the constants are nans, then the whole thing returns
1914 // true.
1915 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001916 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001917
Chris Lattner0a8191e2010-01-05 07:50:36 +00001918 // Otherwise, no need to compare the two constants, compare the
1919 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001920 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001921 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001922
Chris Lattner0a8191e2010-01-05 07:50:36 +00001923 // Handle vector zeros. This occurs because the canonical form of
1924 // "fcmp uno x,x" is "fcmp uno x, 0".
1925 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1926 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001927 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001928
Craig Topperf40110f2014-04-25 05:29:35 +00001929 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001930 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001931
Craig Topperf40110f2014-04-25 05:29:35 +00001932 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001933}
1934
Sanjay Patel18549272015-09-08 18:24:36 +00001935/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001936///
1937/// ((A | B) & C1) | (B & C2)
1938///
1939/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001940///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941/// (A & C1) | B
1942///
1943/// when the XOR of the two constants is "all ones" (-1).
1944Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1945 Value *A, Value *B, Value *C) {
1946 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001947 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001948
Craig Topperf40110f2014-04-25 05:29:35 +00001949 Value *V1 = nullptr;
1950 ConstantInt *CI2 = nullptr;
1951 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952
1953 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001954 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001955
1956 if (V1 == A || V1 == B) {
1957 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1958 return BinaryOperator::CreateOr(NewOp, V1);
1959 }
1960
Craig Topperf40110f2014-04-25 05:29:35 +00001961 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001962}
1963
David Majnemer5d1aeba2014-08-21 05:14:48 +00001964/// \brief This helper function folds:
1965///
1966/// ((A | B) & C1) ^ (B & C2)
1967///
1968/// into:
1969///
1970/// (A & C1) ^ B
1971///
1972/// when the XOR of the two constants is "all ones" (-1).
1973Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
1974 Value *A, Value *B, Value *C) {
1975 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1976 if (!CI1)
1977 return nullptr;
1978
1979 Value *V1 = nullptr;
1980 ConstantInt *CI2 = nullptr;
1981 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1982 return nullptr;
1983
1984 APInt Xor = CI1->getValue() ^ CI2->getValue();
1985 if (!Xor.isAllOnesValue())
1986 return nullptr;
1987
1988 if (V1 == A || V1 == B) {
1989 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1990 return BinaryOperator::CreateXor(NewOp, V1);
1991 }
1992
1993 return nullptr;
1994}
1995
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001996// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1997// here. We should standardize that construct where it is needed or choose some
1998// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001999Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002000 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2002
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002003 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002004 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002005
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002006 if (Value *V = SimplifyOrInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002007 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002008
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002009 // (A&B)|(A&C) -> A&(B|C) etc
2010 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002011 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002012
Craig Topper9d4171a2012-12-20 07:09:41 +00002013 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002014 // purpose is to compute bits we don't care about.
2015 if (SimplifyDemandedInstructionBits(I))
2016 return &I;
2017
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002018 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002019 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002020
Chris Lattner0a8191e2010-01-05 07:50:36 +00002021 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002022 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2024 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2025 Op0->hasOneUse()) {
2026 Value *Or = Builder->CreateOr(X, RHS);
2027 Or->takeName(Op0);
2028 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002029 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002030 }
Craig Topper86173602017-04-04 20:26:25 +00002031 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002032
Craig Topper86173602017-04-04 20:26:25 +00002033 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002034 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2035 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002036
Chad Rosiere5819e22016-05-26 14:58:51 +00002037 // Given an OR instruction, check to see if this is a bswap.
2038 if (Instruction *BSwap = MatchBSwap(I))
2039 return BSwap;
2040
Craig Topperafa07c52017-04-09 06:12:41 +00002041 {
2042 Value *A;
2043 const APInt *C;
2044 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2045 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2046 MaskedValueIsZero(Op1, *C, 0, &I)) {
2047 Value *NOr = Builder->CreateOr(A, Op1);
2048 NOr->takeName(Op0);
2049 return BinaryOperator::CreateXor(NOr,
2050 cast<Instruction>(Op0)->getOperand(1));
2051 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002052
Craig Topperafa07c52017-04-09 06:12:41 +00002053 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2054 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2055 MaskedValueIsZero(Op0, *C, 0, &I)) {
2056 Value *NOr = Builder->CreateOr(A, Op0);
2057 NOr->takeName(Op0);
2058 return BinaryOperator::CreateXor(NOr,
2059 cast<Instruction>(Op1)->getOperand(1));
2060 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002061 }
2062
Craig Topperafa07c52017-04-09 06:12:41 +00002063 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002064
Suyog Sardad64faf62014-07-22 18:09:41 +00002065 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002066 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2067 return BinaryOperator::CreateOr(A, Op1);
2068 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2069 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002070
2071 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002072 // The NOT is guaranteed to be in the RHS by complexity ordering.
2073 if (match(Op1, m_Not(m_Value(A))) &&
2074 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2075 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002076
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002077 // (A & ~B) | (A ^ B) -> (A ^ B)
2078 // (~B & A) | (A ^ B) -> (A ^ B)
2079 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda52324c82014-08-01 04:50:31 +00002080 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2081 return BinaryOperator::CreateXor(A, B);
2082
Sanjay Patel5a443ac2016-12-19 18:35:37 +00002083 // Commute the 'or' operands.
2084 // (A ^ B) | (A & ~B) -> (A ^ B)
2085 // (A ^ B) | (~B & A) -> (A ^ B)
2086 if (match(Op1, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2087 match(Op0, m_Xor(m_Specific(A), m_Specific(B))))
Suyog Sarda52324c82014-08-01 04:50:31 +00002088 return BinaryOperator::CreateXor(A, B);
2089
Chris Lattner0a8191e2010-01-05 07:50:36 +00002090 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002091 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002092 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2093 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002094 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002095 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2096 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002098 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002099 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002100 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002102 ((V1 == B &&
2103 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2104 (V2 == B &&
2105 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002106 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002107 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002108 // Or commutes, try both ways.
2109 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002110 ((V1 == A &&
2111 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2112 (V2 == A &&
2113 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002114 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002115 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002116
Chris Lattner95188692010-01-11 06:55:24 +00002117 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002118 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002119 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002120 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2121 (C3->getValue() & ~C1->getValue()) == 0 &&
2122 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2123 (C4->getValue() & ~C2->getValue()) == 0) {
2124 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2125 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002126 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002127 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002128 }
2129 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002130
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002131 // Don't try to form a select if it's unlikely that we'll get rid of at
2132 // least one of the operands. A select is generally more expensive than the
2133 // 'or' that it is replacing.
2134 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2135 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2136 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2137 return replaceInstUsesWith(I, V);
2138 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2139 return replaceInstUsesWith(I, V);
2140 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2141 return replaceInstUsesWith(I, V);
2142 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2143 return replaceInstUsesWith(I, V);
2144 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2145 return replaceInstUsesWith(I, V);
2146 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2147 return replaceInstUsesWith(I, V);
2148 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2149 return replaceInstUsesWith(I, V);
2150 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2151 return replaceInstUsesWith(I, V);
2152 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002153
2154 // ((A&~B)|(~A&B)) -> A^B
2155 if ((match(C, m_Not(m_Specific(D))) &&
2156 match(B, m_Not(m_Specific(A)))))
2157 return BinaryOperator::CreateXor(A, D);
2158 // ((~B&A)|(~A&B)) -> A^B
2159 if ((match(A, m_Not(m_Specific(D))) &&
2160 match(B, m_Not(m_Specific(C)))))
2161 return BinaryOperator::CreateXor(C, D);
2162 // ((A&~B)|(B&~A)) -> A^B
2163 if ((match(C, m_Not(m_Specific(B))) &&
2164 match(D, m_Not(m_Specific(A)))))
2165 return BinaryOperator::CreateXor(A, B);
2166 // ((~B&A)|(B&~A)) -> A^B
2167 if ((match(A, m_Not(m_Specific(B))) &&
2168 match(D, m_Not(m_Specific(C)))))
2169 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002170
2171 // ((A|B)&1)|(B&-2) -> (A&1) | B
2172 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2173 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2174 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2175 if (Ret) return Ret;
2176 }
2177 // (B&-2)|((A|B)&1) -> (A&1) | B
2178 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2179 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2180 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2181 if (Ret) return Ret;
2182 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002183 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2184 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2185 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2186 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2187 if (Ret) return Ret;
2188 }
2189 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2190 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2191 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2192 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2193 if (Ret) return Ret;
2194 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002195 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002196
David Majnemer42af3602014-07-30 21:26:37 +00002197 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2198 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2199 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2200 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2201 return BinaryOperator::CreateOr(Op0, C);
2202
2203 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2204 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2205 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2206 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2207 return BinaryOperator::CreateOr(Op1, C);
2208
David Majnemerf1eda232014-08-14 06:41:38 +00002209 // ((B | C) & A) | B -> B | (A & C)
2210 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2211 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2212
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002213 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2214 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002215
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002216 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002217 bool SwappedForXor = false;
2218 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002219 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002220 SwappedForXor = true;
2221 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002222
2223 // A | ( A ^ B) -> A | B
2224 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002225 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002226 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2227 if (Op0 == A || Op0 == B)
2228 return BinaryOperator::CreateOr(A, B);
2229
Chad Rosier7813dce2012-04-26 23:29:14 +00002230 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2231 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2232 return BinaryOperator::CreateOr(A, B);
2233
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002234 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2235 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2236 return BinaryOperator::CreateOr(Not, Op0);
2237 }
2238 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2239 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2240 return BinaryOperator::CreateOr(Not, Op0);
2241 }
2242 }
2243
2244 // A | ~(A | B) -> A | ~B
2245 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002246 if (match(Op1, m_Not(m_Value(A))))
2247 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002248 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2249 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2250 B->getOpcode() == Instruction::Xor)) {
2251 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2252 B->getOperand(0);
2253 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2254 return BinaryOperator::CreateOr(Not, Op0);
2255 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002256
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002257 // (A & B) | (~A ^ B) -> (~A ^ B)
2258 // (A & B) | (B ^ ~A) -> (~A ^ B)
2259 // (B & A) | (~A ^ B) -> (~A ^ B)
2260 // (B & A) | (B ^ ~A) -> (~A ^ B)
2261 // The match order is important: match the xor first because the 'not'
2262 // operation defines 'A'. We do not need to match the xor as Op0 because the
2263 // xor was canonicalized to Op1 above.
2264 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2265 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002266 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2267
Eli Friedmane06535b2012-03-16 00:52:42 +00002268 if (SwappedForXor)
2269 std::swap(Op0, Op1);
2270
David Majnemer3d6f80b2014-11-28 19:58:29 +00002271 {
2272 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2273 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2274 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002275 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002276 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002277
David Majnemer3d6f80b2014-11-28 19:58:29 +00002278 // TODO: Make this recursive; it's a little tricky because an arbitrary
2279 // number of 'or' instructions might have to be created.
2280 Value *X, *Y;
2281 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2282 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2283 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002284 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002285 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2286 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002287 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002288 }
2289 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2290 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2291 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002292 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002293 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2294 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002295 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002296 }
2297 }
2298
Chris Lattner4e8137d2010-02-11 06:26:33 +00002299 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2300 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2301 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002302 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002303 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002304
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002305 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2306 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002307
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002308 // 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 +00002309 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002310 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002311 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002312 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002313 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002314 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2315
Owen Andersonc237a842010-09-13 17:59:27 +00002316 // Note: If we've gotten to the point of visiting the outer OR, then the
2317 // inner one couldn't be simplified. If it was a constant, then it won't
2318 // be simplified by a later pass either, so we try swapping the inner/outer
2319 // ORs in the hopes that we'll be able to simplify it this way.
2320 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002321 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002322 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2323 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2324 Value *Inner = Builder->CreateOr(A, Op1);
2325 Inner->takeName(Op0);
2326 return BinaryOperator::CreateOr(Inner, C1);
2327 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002328
Bill Wendling23242092013-02-16 23:41:36 +00002329 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2330 // Since this OR statement hasn't been optimized further yet, we hope
2331 // that this transformation will allow the new ORs to be optimized.
2332 {
Craig Topperf40110f2014-04-25 05:29:35 +00002333 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002334 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2335 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2336 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2337 Value *orTrue = Builder->CreateOr(A, C);
2338 Value *orFalse = Builder->CreateOr(B, D);
2339 return SelectInst::Create(X, orTrue, orFalse);
2340 }
2341 }
2342
Craig Topperf40110f2014-04-25 05:29:35 +00002343 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002344}
2345
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002346// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2347// here. We should standardize that construct where it is needed or choose some
2348// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002349Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002350 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002351 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2352
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002353 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002354 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002355
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002356 if (Value *V = SimplifyXorInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002357 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002358
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002359 // (A&B)^(A&C) -> A&(B^C) etc
2360 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002361 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002362
Craig Topper9d4171a2012-12-20 07:09:41 +00002363 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002364 // purpose is to compute bits we don't care about.
2365 if (SimplifyDemandedInstructionBits(I))
2366 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002367
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002368 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002369 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002370
Chris Lattner0a8191e2010-01-05 07:50:36 +00002371 // Is this a ~ operation?
2372 if (Value *NotOp = dyn_castNotVal(&I)) {
2373 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002374 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002375 Op0I->getOpcode() == Instruction::Or) {
2376 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2377 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2378 if (dyn_castNotVal(Op0I->getOperand(1)))
2379 Op0I->swapOperands();
2380 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2381 Value *NotY =
2382 Builder->CreateNot(Op0I->getOperand(1),
2383 Op0I->getOperand(1)->getName()+".not");
2384 if (Op0I->getOpcode() == Instruction::And)
2385 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2386 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2387 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002388
Chris Lattner0a8191e2010-01-05 07:50:36 +00002389 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2390 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002391 if (IsFreeToInvert(Op0I->getOperand(0),
2392 Op0I->getOperand(0)->hasOneUse()) &&
2393 IsFreeToInvert(Op0I->getOperand(1),
2394 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002395 Value *NotX =
2396 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2397 Value *NotY =
2398 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2399 if (Op0I->getOpcode() == Instruction::And)
2400 return BinaryOperator::CreateOr(NotX, NotY);
2401 return BinaryOperator::CreateAnd(NotX, NotY);
2402 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002403
2404 } else if (Op0I->getOpcode() == Instruction::AShr) {
2405 // ~(~X >>s Y) --> (X >>s Y)
2406 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2407 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002408 }
2409 }
2410 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002411
Benjamin Kramer443c7962015-02-12 20:26:46 +00002412 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2413 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002414 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002415 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2416 return CmpInst::Create(CI->getOpcode(),
2417 CI->getInversePredicate(),
2418 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002419 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002420
Craig Topper9d1821b2017-04-09 06:12:31 +00002421 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002422 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2423 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2424 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2425 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2426 Instruction::CastOps Opcode = Op0C->getOpcode();
2427 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002428 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002429 Op0C->getDestTy()))) {
2430 CI->setPredicate(CI->getInversePredicate());
2431 return CastInst::Create(Opcode, CI, Op0C->getType());
2432 }
2433 }
2434 }
2435 }
2436
2437 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2438 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002439 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2441 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002442 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2443 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002445
Chris Lattner0a8191e2010-01-05 07:50:36 +00002446 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2447 if (Op0I->getOpcode() == Instruction::Add) {
2448 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002449 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002450 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002451 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2452 Op0I->getOperand(0));
Craig Topper9d1821b2017-04-09 06:12:31 +00002453 } else if (RHSC->getValue().isSignBit()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002454 // (X + C) ^ signbit -> (X + C + signbit)
Craig Topper9d1821b2017-04-09 06:12:31 +00002455 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2457
2458 }
2459 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002460 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002461 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2462 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002463 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002464 // Anything in both C1 and C2 is known to be zero, remove it from
2465 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002466 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002467 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002468 ConstantExpr::getNot(CommonBits));
2469 Worklist.Add(Op0I);
2470 I.setOperand(0, Op0I->getOperand(0));
2471 I.setOperand(1, NewRHS);
2472 return &I;
2473 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002474 } else if (Op0I->getOpcode() == Instruction::LShr) {
2475 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2476 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002477 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002478 ConstantInt *C1;
2479 if (Op0I->hasOneUse() &&
2480 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2481 E1->getOpcode() == Instruction::Xor &&
2482 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2483 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002484 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002485 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2486 FoldConst ^= C3->getValue();
2487 // Prepare the two operands.
2488 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2489 Opnd0->takeName(Op0I);
2490 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2491 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2492
2493 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2494 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002495 }
2496 }
2497 }
Craig Topper86173602017-04-04 20:26:25 +00002498 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002499
Craig Topper86173602017-04-04 20:26:25 +00002500 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002501 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2502 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503
Craig Topper76394602017-04-10 06:53:23 +00002504 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002505 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002506 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002507 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002508 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002509 std::swap(A, B);
2510 }
2511 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002512 I.swapOperands(); // Simplified below.
2513 std::swap(Op0, Op1);
2514 }
Craig Topper76394602017-04-10 06:53:23 +00002515 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002516 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002517 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002518 std::swap(A, B);
2519 }
2520 if (B == Op0) { // A^(B&A) -> (B&A)^A
2521 I.swapOperands(); // Simplified below.
2522 std::swap(Op0, Op1);
2523 }
2524 }
2525 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002526
Craig Topper76394602017-04-10 06:53:23 +00002527 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002528 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002529 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002530 if (A == Op1) // (B|A)^B == (A|B)^B
2531 std::swap(A, B);
2532 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002533 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002534 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002535 if (A == Op1) // (A&B)^A -> (B&A)^A
2536 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002537 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002538 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002539 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002540 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002541 }
2542 }
2543 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002544
Craig Topper76394602017-04-10 06:53:23 +00002545 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002546 Value *A, *B, *C, *D;
2547 // (A & B)^(A | B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002548 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2549 match(Op1, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002550 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002551 return BinaryOperator::CreateXor(A, B);
2552 }
2553 // (A | B)^(A & B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002554 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2555 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002556 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002557 return BinaryOperator::CreateXor(A, B);
2558 }
David Majnemer698dca02014-08-14 06:46:25 +00002559 // (A | ~B) ^ (~A | B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002560 // (~B | A) ^ (~A | B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002561 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2562 match(Op1, m_Or(m_Not(m_Specific(A)), m_Specific(B))))
David Majnemer698dca02014-08-14 06:46:25 +00002563 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002564
David Majnemer698dca02014-08-14 06:46:25 +00002565 // (~A | B) ^ (A | ~B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002566 if (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2567 match(Op1, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
David Majnemer698dca02014-08-14 06:46:25 +00002568 return BinaryOperator::CreateXor(A, B);
2569 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002570 // (A & ~B) ^ (~A & B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002571 // (~B & A) ^ (~A & B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002572 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2573 match(Op1, m_And(m_Not(m_Specific(A)), m_Specific(B))))
Mayur Pandey960507b2014-08-19 08:19:19 +00002574 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002575
Mayur Pandey960507b2014-08-19 08:19:19 +00002576 // (~A & B) ^ (A & ~B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002577 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2578 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
Mayur Pandey960507b2014-08-19 08:19:19 +00002579 return BinaryOperator::CreateXor(A, B);
2580 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002581 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002582 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2583 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002584 if (D == A)
2585 return BinaryOperator::CreateXor(
2586 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2587 if (D == B)
2588 return BinaryOperator::CreateXor(
2589 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002590 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002591 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002592 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2593 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002594 if (D == A)
2595 return BinaryOperator::CreateXor(
2596 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2597 if (D == B)
2598 return BinaryOperator::CreateXor(
2599 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002600 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002601 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002602 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002603 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002604 return BinaryOperator::CreateOr(A, B);
2605 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002606 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002607 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002608 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002609 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002610
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002611 // (A & ~B) ^ ~A -> ~(A & B)
2612 // (~B & A) ^ ~A -> ~(A & B)
2613 Value *A, *B;
2614 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002615 match(Op1, m_Not(m_Specific(A))))
2616 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2617
David Majnemerb0761a02016-12-21 19:21:59 +00002618 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002619 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
David Majnemerb0761a02016-12-21 19:21:59 +00002620 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002621 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2622 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2623 LHS->getOperand(1) == RHS->getOperand(0))
2624 LHS->swapOperands();
2625 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2626 LHS->getOperand(1) == RHS->getOperand(1)) {
2627 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2628 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2629 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002630 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002631 getNewICmpValue(isSigned, Code, Op0, Op1,
2632 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002633 }
2634 }
2635
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002636 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2637 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002638
Craig Topperf40110f2014-04-25 05:29:35 +00002639 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002640}