blob: f320f125bf6bfcc6b6f2017419d87098a6f07291 [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 Patel7cfe4162017-04-14 19:23:50 +0000727static Value *
728foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
729 bool JoinedByAnd,
730 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000731 Value *X = LHS->getOperand(0);
732 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000733 return nullptr;
734
Sanjay Patelef9f5862017-04-15 17:55:06 +0000735 const APInt *C1, *C2;
736 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
737 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000738 return nullptr;
739
740 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
741 ICmpInst::Predicate Pred = LHS->getPredicate();
742 if (Pred != RHS->getPredicate())
743 return nullptr;
744 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
745 return nullptr;
746 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
747 return nullptr;
748
749 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000750 if (C1->ugt(*C2))
751 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000752
Sanjay Patelef9f5862017-04-15 17:55:06 +0000753 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000754 if (Xor.isPowerOf2()) {
755 // If LHSC and RHSC differ by only one bit, then set that bit in X and
756 // compare against the larger constant:
757 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
758 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
759 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
760 // 'and' because that may lead to smaller codegen from a smaller constant.
761 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000762 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000763 }
764
765 // Special case: get the ordering right when the values wrap around zero.
766 // Ie, we assumed the constants were unsigned when swapping earlier.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000767 if (*C1 == 0 && C2->isAllOnesValue())
768 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000769
Sanjay Patelef9f5862017-04-15 17:55:06 +0000770 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000771 // (X == 13 || X == 14) --> X - 13 <=u 1
772 // (X != 13 && X != 14) --> X - 13 >u 1
773 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000774 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000775 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
776 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
777 }
778
779 return nullptr;
780}
781
Sanjay Patel18549272015-09-08 18:24:36 +0000782/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000783Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000784 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000785
786 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000787 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000788 if (LHS->getOperand(0) == RHS->getOperand(1) &&
789 LHS->getOperand(1) == RHS->getOperand(0))
790 LHS->swapOperands();
791 if (LHS->getOperand(0) == RHS->getOperand(0) &&
792 LHS->getOperand(1) == RHS->getOperand(1)) {
793 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
794 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
795 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000796 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000797 }
798 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000799
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000800 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000801 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000802 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000803
Erik Ecksteind1817522014-12-03 10:39:15 +0000804 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
805 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
806 return V;
807
808 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
809 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
810 return V;
811
Sanjay Patelef9f5862017-04-15 17:55:06 +0000812 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
813 return V;
814
Chris Lattner0a8191e2010-01-05 07:50:36 +0000815 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000816 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000817 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
818 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
819 if (!LHSC || !RHSC)
820 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000821
Sanjay Patel519a87a2017-04-05 17:38:34 +0000822 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000823 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000824 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000825 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000826 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
827 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000828 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000829 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000830 }
831 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000832
Benjamin Kramer101720f2011-04-28 20:09:57 +0000833 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000834 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000835 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000836 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
837 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000838 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000839 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000840
841 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000842 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000843 if (match(RHS0, m_Trunc(m_Value(V))) &&
844 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000845 SmallC = RHSC;
846 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000847 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
848 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000849 SmallC = LHSC;
850 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000851 }
852
Sanjay Patel519a87a2017-04-05 17:38:34 +0000853 if (SmallC && BigC) {
854 unsigned BigBitSize = BigC->getType()->getBitWidth();
855 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000856
857 // Check that the low bits are zero.
858 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000859 if ((Low & AndC->getValue()) == 0 && (Low & BigC->getValue()) == 0) {
860 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
861 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
862 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
863 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000864 }
865 }
866 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000867
Chris Lattner0a8191e2010-01-05 07:50:36 +0000868 // From here on, we only handle:
869 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000870 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000871 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000872
Sanjay Patel519a87a2017-04-05 17:38:34 +0000873 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
874 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
875 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
876 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
877 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000878 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000879
Chris Lattner0a8191e2010-01-05 07:50:36 +0000880 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000881 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000882 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000883
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 // Ensure that the larger constant is on the RHS.
885 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000886 if (CmpInst::isSigned(PredL) ||
887 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000888 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000889 else
890 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000891
Chris Lattner0a8191e2010-01-05 07:50:36 +0000892 if (ShouldSwap) {
893 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000894 std::swap(LHSC, RHSC);
895 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000896 }
897
Dan Gohman4a618822010-02-10 16:03:48 +0000898 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000899 // comparing a value against two constants and and'ing the result
900 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000901 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
902 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000904 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000905
Sanjay Patel519a87a2017-04-05 17:38:34 +0000906 switch (PredL) {
907 default:
908 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000909 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000910 switch (PredR) {
911 default:
912 llvm_unreachable("Unknown integer condition code!");
913 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
914 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
915 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000916 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 }
918 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000919 switch (PredR) {
920 default:
921 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000922 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000923 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000924 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000925 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000926 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000927 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000928 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000929 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000930 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000931 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000932 break; // (X != 13 & X s< 15) -> no change
933 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
934 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
935 case ICmpInst::ICMP_SGT: // (X != 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 Patel7cfe4162017-04-14 19:23:50 +0000938 // Potential folds for this case should already be handled.
939 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 }
941 break;
942 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000943 switch (PredR) {
944 default:
945 llvm_unreachable("Unknown integer condition code!");
946 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
947 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000948 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000949 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
950 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000951 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 }
953 break;
954 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000955 switch (PredR) {
956 default:
957 llvm_unreachable("Unknown integer condition code!");
Sanjay Patel519a87a2017-04-05 17:38:34 +0000958 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
959 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000960 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000961 }
962 break;
963 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000964 switch (PredR) {
965 default:
966 llvm_unreachable("Unknown integer condition code!");
967 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
968 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000969 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000970 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000971 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000972 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000973 break; // (X u> 13 & X != 15) -> no change
974 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000975 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
976 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 }
978 break;
979 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000980 switch (PredR) {
981 default:
982 llvm_unreachable("Unknown integer condition code!");
983 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
984 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000985 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000986 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000987 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000988 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000989 break; // (X s> 13 & X != 15) -> no change
990 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000991 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000992 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000993 }
994 break;
995 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000996
Craig Topperf40110f2014-04-25 05:29:35 +0000997 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998}
999
Sanjay Patel18549272015-09-08 18:24:36 +00001000/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1001/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001002Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001003 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1004 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1005 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1006
1007 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1008 // Swap RHS operands to match LHS.
1009 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1010 std::swap(Op1LHS, Op1RHS);
1011 }
1012
1013 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1014 // Suppose the relation between x and y is R, where R is one of
1015 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1016 // testing the desired relations.
1017 //
1018 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1019 // bool(R & CC0) && bool(R & CC1)
1020 // = bool((R & CC0) & (R & CC1))
1021 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1022 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1023 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1024 Builder);
1025
Chris Lattner0a8191e2010-01-05 07:50:36 +00001026 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1027 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001028 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001029 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001030
Chris Lattner0a8191e2010-01-05 07:50:36 +00001031 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1032 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1033 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1034 // If either of the constants are nans, then the whole thing returns
1035 // false.
1036 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001037 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001038 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001039 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001040
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041 // Handle vector zeros. This occurs because the canonical form of
1042 // "fcmp ord x,x" is "fcmp ord x, 0".
1043 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1044 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001045 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001046 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001047 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001048
Craig Topperf40110f2014-04-25 05:29:35 +00001049 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001050}
1051
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001052/// Match De Morgan's Laws:
1053/// (~A & ~B) == (~(A | B))
1054/// (~A | ~B) == (~(A & B))
1055static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1056 InstCombiner::BuilderTy *Builder) {
1057 auto Opcode = I.getOpcode();
1058 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1059 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001060 // Flip the logic operation.
1061 if (Opcode == Instruction::And)
1062 Opcode = Instruction::Or;
1063 else
1064 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001065
1066 Value *Op0 = I.getOperand(0);
1067 Value *Op1 = I.getOperand(1);
1068 // TODO: Use pattern matchers instead of dyn_cast.
1069 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1070 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1071 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001072 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1073 I.getName() + ".demorgan");
1074 return BinaryOperator::CreateNot(LogicOp);
1075 }
1076
1077 return nullptr;
1078}
1079
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001080bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1081 Value *CastSrc = CI->getOperand(0);
1082
1083 // Noop casts and casts of constants should be eliminated trivially.
1084 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1085 return false;
1086
1087 // If this cast is paired with another cast that can be eliminated, we prefer
1088 // to have it eliminated.
1089 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1090 if (isEliminableCastPair(PrecedingCI, CI))
1091 return false;
1092
1093 // If this is a vector sext from a compare, then we don't want to break the
1094 // idiom where each element of the extended vector is either zero or all ones.
1095 if (CI->getOpcode() == Instruction::SExt &&
1096 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1097 return false;
1098
1099 return true;
1100}
1101
Sanjay Patel60312bc42016-09-12 00:16:23 +00001102/// Fold {and,or,xor} (cast X), C.
1103static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1104 InstCombiner::BuilderTy *Builder) {
1105 Constant *C;
1106 if (!match(Logic.getOperand(1), m_Constant(C)))
1107 return nullptr;
1108
1109 auto LogicOpc = Logic.getOpcode();
1110 Type *DestTy = Logic.getType();
1111 Type *SrcTy = Cast->getSrcTy();
1112
1113 // If the first operand is bitcast, move the logic operation ahead of the
1114 // bitcast (do the logic operation in the original type). This can eliminate
1115 // bitcasts and allow combines that would otherwise be impeded by the bitcast.
1116 Value *X;
1117 if (match(Cast, m_BitCast(m_Value(X)))) {
1118 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1119 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, NewConstant);
1120 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1121 }
1122
1123 // Similarly, move the logic operation ahead of a zext if the constant is
1124 // unchanged in the smaller source type. Performing the logic in a smaller
1125 // type may provide more information to later folds, and the smaller logic
1126 // instruction may be cheaper (particularly in the case of vectors).
1127 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1128 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1129 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1130 if (ZextTruncC == C) {
1131 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1132 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1133 return new ZExtInst(NewOp, DestTy);
1134 }
1135 }
1136
1137 return nullptr;
1138}
1139
1140/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001141Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001142 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001143 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001144
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001146 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001147 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001148 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001149
Sanjay Patel9bba7502016-03-03 19:19:04 +00001150 // This must be a cast from an integer or integer vector source type to allow
1151 // transformation of the logic operation to the source type.
1152 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001153 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001154 if (!SrcTy->isIntOrIntVectorTy())
1155 return nullptr;
1156
Sanjay Patel60312bc42016-09-12 00:16:23 +00001157 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1158 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001159
Sanjay Patel9bba7502016-03-03 19:19:04 +00001160 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1161 if (!Cast1)
1162 return nullptr;
1163
1164 // Both operands of the logic operation are casts. The casts must be of the
1165 // same type for reduction.
1166 auto CastOpcode = Cast0->getOpcode();
1167 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001168 return nullptr;
1169
1170 Value *Cast0Src = Cast0->getOperand(0);
1171 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001172
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001173 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001174 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001175 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1176 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001177 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001178 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001179
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001180 // For now, only 'and'/'or' have optimizations after this.
1181 if (LogicOpc == Instruction::Xor)
1182 return nullptr;
1183
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001184 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001185 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001186 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1187 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1188 if (ICmp0 && ICmp1) {
1189 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1190 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1191 if (Res)
1192 return CastInst::Create(CastOpcode, Res, DestTy);
1193 return nullptr;
1194 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001195
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001196 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001197 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001198 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1199 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1200 if (FCmp0 && FCmp1) {
1201 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1202 : FoldOrOfFCmps(FCmp0, FCmp1);
1203 if (Res)
1204 return CastInst::Create(CastOpcode, Res, DestTy);
1205 return nullptr;
1206 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001207
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001208 return nullptr;
1209}
1210
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001211static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1212 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1213
1214 // Canonicalize SExt or Not to the LHS
1215 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1216 std::swap(Op0, Op1);
1217 }
1218
1219 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1220 Value *X = nullptr;
1221 if (match(Op0, m_SExt(m_Value(X))) &&
1222 X->getType()->getScalarType()->isIntegerTy(1)) {
1223 Value *Zero = Constant::getNullValue(Op1->getType());
1224 return SelectInst::Create(X, Op1, Zero);
1225 }
1226
1227 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1228 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1229 X->getType()->getScalarType()->isIntegerTy(1)) {
1230 Value *Zero = Constant::getNullValue(Op0->getType());
1231 return SelectInst::Create(X, Zero, Op1);
1232 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001233
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001234 return nullptr;
1235}
1236
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001237// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1238// here. We should standardize that construct where it is needed or choose some
1239// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001240Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001241 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1243
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001244 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001245 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001246
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001247 if (Value *V = SimplifyAndInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001248 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001249
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001250 // (A|B)&(A|C) -> A|(B&C) etc
1251 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001252 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001253
Craig Topper9d4171a2012-12-20 07:09:41 +00001254 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001255 // purpose is to compute bits we don't care about.
1256 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001257 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001258
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001259 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001260 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001261
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1263 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001264
1265 // Optimize a variety of ((val OP C1) & C2) combinations...
1266 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1267 Value *Op0LHS = Op0I->getOperand(0);
1268 Value *Op0RHS = Op0I->getOperand(1);
1269 switch (Op0I->getOpcode()) {
1270 default: break;
1271 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001272 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273 // If the mask is only needed on one incoming arm, push it up.
1274 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001275
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001276 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001277 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001278 // Not masking anything out for the LHS, move to RHS.
1279 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1280 Op0RHS->getName()+".masked");
1281 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1282 }
1283 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001284 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001285 // Not masking anything out for the RHS, move to LHS.
1286 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1287 Op0LHS->getName()+".masked");
1288 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1289 }
1290
1291 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001292 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001293 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001294 // -x & 1 -> x & 1
1295 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1296 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1297
Chris Lattner0a8191e2010-01-05 07:50:36 +00001298 break;
1299
1300 case Instruction::Shl:
1301 case Instruction::LShr:
1302 // (1 << x) & 1 --> zext(x == 0)
1303 // (1 >> x) & 1 --> zext(x == 0)
1304 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1305 Value *NewICmp =
1306 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1307 return new ZExtInst(NewICmp, I.getType());
1308 }
1309 break;
1310 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001311
David Majnemerde55c602017-01-17 18:08:06 +00001312 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1313 // of X and OP behaves well when given trunc(C1) and X.
1314 switch (Op0I->getOpcode()) {
1315 default:
1316 break;
1317 case Instruction::Xor:
1318 case Instruction::Or:
1319 case Instruction::Mul:
1320 case Instruction::Add:
1321 case Instruction::Sub:
1322 Value *X;
1323 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001324 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001325 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1326 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1327 Value *BinOp;
1328 if (isa<ZExtInst>(Op0LHS))
1329 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1330 else
1331 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1332 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1333 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1334 return new ZExtInst(And, I.getType());
1335 }
1336 }
1337 }
1338
Chris Lattner0a8191e2010-01-05 07:50:36 +00001339 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1340 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1341 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001342 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001343
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001344 // If this is an integer truncation, and if the source is an 'and' with
1345 // immediate, transform it. This frequently occurs for bitfield accesses.
1346 {
Craig Topperf40110f2014-04-25 05:29:35 +00001347 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001348 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1349 // Change: and (trunc (and X, YC) to T), C2
1350 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001351 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001352 // other simplifications.
1353 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1354 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1355 C3 = ConstantExpr::getAnd(C3, AndRHS);
1356 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001357 }
1358 }
Craig Topper86173602017-04-04 20:26:25 +00001359 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001360
Craig Topper86173602017-04-04 20:26:25 +00001361 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001362 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1363 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001364
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001365 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1366 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001367
Chris Lattner0a8191e2010-01-05 07:50:36 +00001368 {
Craig Topperf40110f2014-04-25 05:29:35 +00001369 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001370 // (A|B) & ~(A&B) -> A^B
1371 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1372 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1373 ((A == C && B == D) || (A == D && B == C)))
1374 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001375
Chris Lattner0a8191e2010-01-05 07:50:36 +00001376 // ~(A&B) & (A|B) -> A^B
1377 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1378 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1379 ((A == C && B == D) || (A == D && B == C)))
1380 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001381
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001382 // A&(A^B) => A & ~B
1383 {
1384 Value *tmpOp0 = Op0;
1385 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001386 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001387 if (A == Op1 || B == Op1 ) {
1388 tmpOp1 = Op0;
1389 tmpOp0 = Op1;
1390 // Simplify below
1391 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001393
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001394 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001395 if (B == tmpOp0) {
1396 std::swap(A, B);
1397 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001398 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001399 // A is originally -1 (or a vector of -1 and undefs), then we enter
1400 // an endless loop. By checking that A is non-constant we ensure that
1401 // we will never get to the loop.
1402 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001403 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001404 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405 }
1406
1407 // (A&((~A)|B)) -> A&B
1408 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1409 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1410 return BinaryOperator::CreateAnd(A, Op1);
1411 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1412 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1413 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001414
1415 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1416 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1417 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1418 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1419 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1420
1421 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1422 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1423 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1424 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1425 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001426
1427 // (A | B) & ((~A) ^ B) -> (A & B)
1428 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1429 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1430 return BinaryOperator::CreateAnd(A, B);
1431
1432 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001433 // ((~A) ^ B) & (B | A) -> (A & B)
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001434 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001435 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001436 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001437 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001438
David Majnemer5e96f1b2014-08-30 06:18:20 +00001439 {
1440 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1441 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1442 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001443 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001444 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001445
David Majnemer5e96f1b2014-08-30 06:18:20 +00001446 // TODO: Make this recursive; it's a little tricky because an arbitrary
1447 // number of 'and' instructions might have to be created.
1448 Value *X, *Y;
1449 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1450 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1451 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001452 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001453 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1454 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001455 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001456 }
1457 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1458 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1459 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001460 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001461 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1462 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001463 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001464 }
1465 }
1466
Chris Lattner4e8137d2010-02-11 06:26:33 +00001467 // If and'ing two fcmp, try combine them into one.
1468 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1469 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001470 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001472
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001473 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1474 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001475
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001476 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1477 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001478
Craig Topperf40110f2014-04-25 05:29:35 +00001479 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001480}
1481
Chad Rosiera00df492016-05-25 16:22:14 +00001482/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1483/// insert the new intrinsic and return it.
1484Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001485 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1486
1487 // Look through zero extends.
1488 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1489 Op0 = Ext->getOperand(0);
1490
1491 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1492 Op1 = Ext->getOperand(0);
1493
1494 // (A | B) | C and A | (B | C) -> bswap if possible.
1495 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1496 match(Op1, m_Or(m_Value(), m_Value()));
1497
1498 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1499 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1500 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1501
1502 // (A & B) | (C & D) -> bswap if possible.
1503 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1504 match(Op1, m_And(m_Value(), m_Value()));
1505
1506 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1507 return nullptr;
1508
James Molloyf01488e2016-01-15 09:20:19 +00001509 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001510 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001511 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001512 Instruction *LastInst = Insts.pop_back_val();
1513 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001514
James Molloyf01488e2016-01-15 09:20:19 +00001515 for (auto *Inst : Insts)
1516 Worklist.Add(Inst);
1517 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001518}
1519
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001520/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1521static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1522 unsigned NumElts = C1->getType()->getVectorNumElements();
1523 for (unsigned i = 0; i != NumElts; ++i) {
1524 Constant *EltC1 = C1->getAggregateElement(i);
1525 Constant *EltC2 = C2->getAggregateElement(i);
1526 if (!EltC1 || !EltC2)
1527 return false;
1528
1529 // One element must be all ones, and the other must be all zeros.
1530 // FIXME: Allow undef elements.
1531 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1532 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1533 return false;
1534 }
1535 return true;
1536}
1537
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001538/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1539/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1540/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001541static Value *getSelectCondition(Value *A, Value *B,
1542 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001543 // If these are scalars or vectors of i1, A can be used directly.
1544 Type *Ty = A->getType();
1545 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1546 return A;
1547
1548 // If A and B are sign-extended, look through the sexts to find the booleans.
1549 Value *Cond;
1550 if (match(A, m_SExt(m_Value(Cond))) &&
1551 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1552 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1553 m_SExt(m_Not(m_Specific(Cond))))))
1554 return Cond;
1555
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001556 // All scalar (and most vector) possibilities should be handled now.
1557 // Try more matches that only apply to non-splat constant vectors.
1558 if (!Ty->isVectorTy())
1559 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001560
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001561 // If both operands are constants, see if the constants are inverse bitmasks.
1562 Constant *AC, *BC;
1563 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1564 areInverseVectorBitmasks(AC, BC))
1565 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1566
1567 // If both operands are xor'd with constants using the same sexted boolean
1568 // operand, see if the constants are inverse bitmasks.
1569 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1570 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1571 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1572 areInverseVectorBitmasks(AC, BC)) {
1573 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1574 return Builder.CreateXor(Cond, AC);
1575 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001576 return nullptr;
1577}
1578
1579/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1580/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001581static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001582 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001583 // The potential condition of the select may be bitcasted. In that case, look
1584 // through its bitcast and the corresponding bitcast of the 'not' condition.
1585 Type *OrigType = A->getType();
1586 Value *SrcA, *SrcB;
Sanjay Patel664514f2016-07-08 21:17:51 +00001587 if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1588 match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001589 A = SrcA;
1590 B = SrcB;
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001591 }
1592
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001593 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001594 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001595 // The bitcasts will either all exist or all not exist. The builder will
1596 // not create unnecessary casts if the types already match.
1597 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1598 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1599 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1600 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001601 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001602
Craig Topperf40110f2014-04-25 05:29:35 +00001603 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001604}
1605
Sanjay Patel18549272015-09-08 18:24:36 +00001606/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001607Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1608 Instruction *CxtI) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001609 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001610
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001611 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1612 // if K1 and K2 are a one-bit mask.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001613 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1614 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001615
Sanjay Patel519a87a2017-04-05 17:38:34 +00001616 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero() &&
1617 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001618
1619 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1620 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1621 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1622 LAnd->getOpcode() == Instruction::And &&
1623 RAnd->getOpcode() == Instruction::And) {
1624
Craig Topperf40110f2014-04-25 05:29:35 +00001625 Value *Mask = nullptr;
1626 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001627 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001628 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001629 &DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001630 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001631 &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001632 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1633 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1634 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001635 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, &AC,
1636 CxtI, &DT) &&
1637 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, &AC,
1638 CxtI, &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001639 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1640 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1641 }
1642
1643 if (Masked)
1644 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1645 }
1646 }
1647
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001648 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1649 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1650 // The original condition actually refers to the following two ranges:
1651 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1652 // We can fold these two ranges if:
1653 // 1) C1 and C2 is unsigned greater than C3.
1654 // 2) The two ranges are separated.
1655 // 3) C1 ^ C2 is one-bit mask.
1656 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1657 // This implies all values in the two ranges differ by exactly one bit.
1658
Sanjay Patel519a87a2017-04-05 17:38:34 +00001659 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1660 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1661 LHSC->getType() == RHSC->getType() &&
1662 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001663
1664 Value *LAdd = LHS->getOperand(0);
1665 Value *RAdd = RHS->getOperand(0);
1666
1667 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001668 ConstantInt *LAddC, *RAddC;
1669 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1670 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1671 LAddC->getValue().ugt(LHSC->getValue()) &&
1672 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001673
Sanjay Patel519a87a2017-04-05 17:38:34 +00001674 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1675 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1676 ConstantInt *MaxAddC = nullptr;
1677 if (LAddC->getValue().ult(RAddC->getValue()))
1678 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001679 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001680 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001681
Sanjay Patel519a87a2017-04-05 17:38:34 +00001682 APInt RRangeLow = -RAddC->getValue();
1683 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1684 APInt LRangeLow = -LAddC->getValue();
1685 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001686 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1687 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1688 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1689 : RRangeLow - LRangeLow;
1690
1691 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001692 RangeDiff.ugt(LHSC->getValue())) {
1693 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001694
Sanjay Patel519a87a2017-04-05 17:38:34 +00001695 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1696 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1697 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001698 }
1699 }
1700 }
1701 }
1702
Chris Lattner0a8191e2010-01-05 07:50:36 +00001703 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001704 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001705 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1706 LHS->getOperand(1) == RHS->getOperand(0))
1707 LHS->swapOperands();
1708 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1709 LHS->getOperand(1) == RHS->getOperand(1)) {
1710 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1711 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1712 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001713 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001714 }
1715 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001716
1717 // handle (roughly):
1718 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001719 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001720 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001721
Sanjay Patele4159d22017-04-10 19:38:36 +00001722 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001723 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1724 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1725 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001726 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001727 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001728 B = LHS0;
1729 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1730 A = RHS0;
1731 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001732 A = RHS->getOperand(1);
1733 }
1734 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1735 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001736 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001737 B = RHS0;
1738 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1739 A = LHS0;
1740 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001741 A = LHS->getOperand(1);
1742 }
1743 if (A && B)
1744 return Builder->CreateICmp(
1745 ICmpInst::ICMP_UGE,
1746 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1747 }
1748
Erik Ecksteind1817522014-12-03 10:39:15 +00001749 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1750 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1751 return V;
1752
1753 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1754 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1755 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001756
Sanjay Patelef9f5862017-04-15 17:55:06 +00001757 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1758 return V;
1759
David Majnemerc2a990b2013-07-05 00:31:17 +00001760 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001761 if (!LHSC || !RHSC)
1762 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001763
Sanjay Patel519a87a2017-04-05 17:38:34 +00001764 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001765 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001766 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001767 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001768 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001769 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001770 }
1771
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001772 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001773 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001774 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1775 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001776 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001777 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001778 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001779 }
1780
Chris Lattner0a8191e2010-01-05 07:50:36 +00001781 // From here on, we only handle:
1782 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001783 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001784 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001785
Sanjay Patel519a87a2017-04-05 17:38:34 +00001786 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1787 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1788 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1789 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1790 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001791 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001792
Chris Lattner0a8191e2010-01-05 07:50:36 +00001793 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001794 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001795 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001796
Chris Lattner0a8191e2010-01-05 07:50:36 +00001797 // Ensure that the larger constant is on the RHS.
1798 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001799 if (CmpInst::isSigned(PredL) ||
1800 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001801 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001802 else
1803 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001804
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805 if (ShouldSwap) {
1806 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001807 std::swap(LHSC, RHSC);
1808 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001810
Dan Gohman4a618822010-02-10 16:03:48 +00001811 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001812 // comparing a value against two constants and or'ing the result
1813 // together. Because of the above check, we know that we only have
1814 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1815 // icmp folding check above), that the two constants are not
1816 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001817 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001818
Sanjay Patel519a87a2017-04-05 17:38:34 +00001819 switch (PredL) {
1820 default:
1821 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001822 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001823 switch (PredR) {
1824 default:
1825 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001826 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001827 // Potential folds for this case should already be handled.
1828 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001829 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1830 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001832 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1833 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1834 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 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_NE:
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 != 13 | X == 15) -> X != 13
1843 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1844 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001845 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001846 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1847 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1848 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001849 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001850 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001851 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001852 switch (PredR) {
1853 default:
1854 llvm_unreachable("Unknown integer condition code!");
1855 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001856 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001857 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1858 // If RHSC is [us]MAXINT, it is always false. Not handling
Chris Lattner0a8191e2010-01-05 07:50:36 +00001859 // this can cause overflow.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001860 if (RHSC->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001861 return LHS;
Sanjay Patele4159d22017-04-10 19:38:36 +00001862 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1863 false, false);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001864 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1865 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001866 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001867 }
1868 break;
1869 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001870 switch (PredR) {
1871 default:
1872 llvm_unreachable("Unknown integer condition code!");
1873 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001874 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001875 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1876 // If RHSC is [us]MAXINT, it is always false. Not handling
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 // this can cause overflow.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001878 if (RHSC->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001879 return LHS;
Sanjay Patele4159d22017-04-10 19:38:36 +00001880 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001881 false);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001882 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1883 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001884 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 }
1886 break;
1887 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001888 switch (PredR) {
1889 default:
1890 llvm_unreachable("Unknown integer condition code!");
1891 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1892 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001893 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001894 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1895 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001896 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 }
1898 break;
1899 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001900 switch (PredR) {
1901 default:
1902 llvm_unreachable("Unknown integer condition code!");
1903 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1904 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001905 return LHS;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001906 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1907 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001908 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909 }
1910 break;
1911 }
Craig Topperf40110f2014-04-25 05:29:35 +00001912 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001913}
1914
Sanjay Patel18549272015-09-08 18:24:36 +00001915/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1916/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001917Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001918 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1919 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1920 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1921
1922 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1923 // Swap RHS operands to match LHS.
1924 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1925 std::swap(Op1LHS, Op1RHS);
1926 }
1927
1928 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1929 // This is a similar transformation to the one in FoldAndOfFCmps.
1930 //
1931 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1932 // bool(R & CC0) || bool(R & CC1)
1933 // = bool((R & CC0) | (R & CC1))
1934 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1935 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1936 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1937 Builder);
1938
Chris Lattner0a8191e2010-01-05 07:50:36 +00001939 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001940 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1944 // If either of the constants are nans, then the whole thing returns
1945 // true.
1946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001947 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001948
Chris Lattner0a8191e2010-01-05 07:50:36 +00001949 // Otherwise, no need to compare the two constants, compare the
1950 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001951 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001953
Chris Lattner0a8191e2010-01-05 07:50:36 +00001954 // Handle vector zeros. This occurs because the canonical form of
1955 // "fcmp uno x,x" is "fcmp uno x, 0".
1956 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1957 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001958 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001959
Craig Topperf40110f2014-04-25 05:29:35 +00001960 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001961 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001962
Craig Topperf40110f2014-04-25 05:29:35 +00001963 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964}
1965
Sanjay Patel18549272015-09-08 18:24:36 +00001966/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967///
1968/// ((A | B) & C1) | (B & C2)
1969///
1970/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001971///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001972/// (A & C1) | B
1973///
1974/// when the XOR of the two constants is "all ones" (-1).
1975Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1976 Value *A, Value *B, Value *C) {
1977 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001978 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001979
Craig Topperf40110f2014-04-25 05:29:35 +00001980 Value *V1 = nullptr;
1981 ConstantInt *CI2 = nullptr;
1982 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001983
1984 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001985 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001986
1987 if (V1 == A || V1 == B) {
1988 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1989 return BinaryOperator::CreateOr(NewOp, V1);
1990 }
1991
Craig Topperf40110f2014-04-25 05:29:35 +00001992 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001993}
1994
David Majnemer5d1aeba2014-08-21 05:14:48 +00001995/// \brief This helper function folds:
1996///
1997/// ((A | B) & C1) ^ (B & C2)
1998///
1999/// into:
2000///
2001/// (A & C1) ^ B
2002///
2003/// when the XOR of the two constants is "all ones" (-1).
2004Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2005 Value *A, Value *B, Value *C) {
2006 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2007 if (!CI1)
2008 return nullptr;
2009
2010 Value *V1 = nullptr;
2011 ConstantInt *CI2 = nullptr;
2012 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2013 return nullptr;
2014
2015 APInt Xor = CI1->getValue() ^ CI2->getValue();
2016 if (!Xor.isAllOnesValue())
2017 return nullptr;
2018
2019 if (V1 == A || V1 == B) {
2020 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2021 return BinaryOperator::CreateXor(NewOp, V1);
2022 }
2023
2024 return nullptr;
2025}
2026
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002027// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2028// here. We should standardize that construct where it is needed or choose some
2029// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002030Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002031 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002032 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2033
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002034 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002035 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002036
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002037 if (Value *V = SimplifyOrInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002038 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002039
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002040 // (A&B)|(A&C) -> A&(B|C) etc
2041 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002042 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002043
Craig Topper9d4171a2012-12-20 07:09:41 +00002044 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002045 // purpose is to compute bits we don't care about.
2046 if (SimplifyDemandedInstructionBits(I))
2047 return &I;
2048
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002049 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002050 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002051
Chris Lattner0a8191e2010-01-05 07:50:36 +00002052 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002053 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002054 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2055 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2056 Op0->hasOneUse()) {
2057 Value *Or = Builder->CreateOr(X, RHS);
2058 Or->takeName(Op0);
2059 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002060 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002061 }
Craig Topper86173602017-04-04 20:26:25 +00002062 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002063
Craig Topper86173602017-04-04 20:26:25 +00002064 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002065 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2066 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002067
Chad Rosiere5819e22016-05-26 14:58:51 +00002068 // Given an OR instruction, check to see if this is a bswap.
2069 if (Instruction *BSwap = MatchBSwap(I))
2070 return BSwap;
2071
Craig Topperafa07c52017-04-09 06:12:41 +00002072 {
2073 Value *A;
2074 const APInt *C;
2075 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2076 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2077 MaskedValueIsZero(Op1, *C, 0, &I)) {
2078 Value *NOr = Builder->CreateOr(A, Op1);
2079 NOr->takeName(Op0);
2080 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002081 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002082 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002083
Craig Topperafa07c52017-04-09 06:12:41 +00002084 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2085 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2086 MaskedValueIsZero(Op0, *C, 0, &I)) {
2087 Value *NOr = Builder->CreateOr(A, Op0);
2088 NOr->takeName(Op0);
2089 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002090 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002091 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002092 }
2093
Craig Topperafa07c52017-04-09 06:12:41 +00002094 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002095
Suyog Sardad64faf62014-07-22 18:09:41 +00002096 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002097 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2098 return BinaryOperator::CreateOr(A, Op1);
2099 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2100 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002101
2102 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002103 // The NOT is guaranteed to be in the RHS by complexity ordering.
2104 if (match(Op1, m_Not(m_Value(A))) &&
2105 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2106 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002107
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002108 // (A & ~B) | (A ^ B) -> (A ^ B)
2109 // (~B & A) | (A ^ B) -> (A ^ B)
2110 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda52324c82014-08-01 04:50:31 +00002111 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2112 return BinaryOperator::CreateXor(A, B);
2113
Sanjay Patel5a443ac2016-12-19 18:35:37 +00002114 // Commute the 'or' operands.
2115 // (A ^ B) | (A & ~B) -> (A ^ B)
2116 // (A ^ B) | (~B & A) -> (A ^ B)
2117 if (match(Op1, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2118 match(Op0, m_Xor(m_Specific(A), m_Specific(B))))
Suyog Sarda52324c82014-08-01 04:50:31 +00002119 return BinaryOperator::CreateXor(A, B);
2120
Chris Lattner0a8191e2010-01-05 07:50:36 +00002121 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002122 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002123 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2124 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002125 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002126 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2127 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002128 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002129 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002130 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002131 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002132 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002133 ((V1 == B &&
2134 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2135 (V2 == B &&
2136 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002137 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002138 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002139 // Or commutes, try both ways.
2140 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002141 ((V1 == A &&
2142 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2143 (V2 == A &&
2144 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002145 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002146 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002147
Chris Lattner95188692010-01-11 06:55:24 +00002148 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002149 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002150 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002151 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2152 (C3->getValue() & ~C1->getValue()) == 0 &&
2153 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2154 (C4->getValue() & ~C2->getValue()) == 0) {
2155 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2156 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002157 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002158 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002159 }
2160 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002161
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002162 // Don't try to form a select if it's unlikely that we'll get rid of at
2163 // least one of the operands. A select is generally more expensive than the
2164 // 'or' that it is replacing.
2165 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2166 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2167 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2168 return replaceInstUsesWith(I, V);
2169 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2170 return replaceInstUsesWith(I, V);
2171 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2172 return replaceInstUsesWith(I, V);
2173 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2174 return replaceInstUsesWith(I, V);
2175 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2176 return replaceInstUsesWith(I, V);
2177 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2178 return replaceInstUsesWith(I, V);
2179 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2180 return replaceInstUsesWith(I, V);
2181 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2182 return replaceInstUsesWith(I, V);
2183 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002184
2185 // ((A&~B)|(~A&B)) -> A^B
2186 if ((match(C, m_Not(m_Specific(D))) &&
2187 match(B, m_Not(m_Specific(A)))))
2188 return BinaryOperator::CreateXor(A, D);
2189 // ((~B&A)|(~A&B)) -> A^B
2190 if ((match(A, m_Not(m_Specific(D))) &&
2191 match(B, m_Not(m_Specific(C)))))
2192 return BinaryOperator::CreateXor(C, D);
2193 // ((A&~B)|(B&~A)) -> A^B
2194 if ((match(C, m_Not(m_Specific(B))) &&
2195 match(D, m_Not(m_Specific(A)))))
2196 return BinaryOperator::CreateXor(A, B);
2197 // ((~B&A)|(B&~A)) -> A^B
2198 if ((match(A, m_Not(m_Specific(B))) &&
2199 match(D, m_Not(m_Specific(C)))))
2200 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002201
2202 // ((A|B)&1)|(B&-2) -> (A&1) | B
2203 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2204 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2205 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2206 if (Ret) return Ret;
2207 }
2208 // (B&-2)|((A|B)&1) -> (A&1) | B
2209 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2210 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2211 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2212 if (Ret) return Ret;
2213 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002214 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2215 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2216 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2217 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2218 if (Ret) return Ret;
2219 }
2220 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2221 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2222 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2223 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2224 if (Ret) return Ret;
2225 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002226 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002227
David Majnemer42af3602014-07-30 21:26:37 +00002228 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2229 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2230 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2231 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2232 return BinaryOperator::CreateOr(Op0, C);
2233
2234 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2235 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2236 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2237 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2238 return BinaryOperator::CreateOr(Op1, C);
2239
David Majnemerf1eda232014-08-14 06:41:38 +00002240 // ((B | C) & A) | B -> B | (A & C)
2241 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2242 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2243
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002244 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2245 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002246
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002247 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002248 bool SwappedForXor = false;
2249 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002250 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002251 SwappedForXor = true;
2252 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002253
2254 // A | ( A ^ B) -> A | B
2255 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002256 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002257 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2258 if (Op0 == A || Op0 == B)
2259 return BinaryOperator::CreateOr(A, B);
2260
Chad Rosier7813dce2012-04-26 23:29:14 +00002261 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2262 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2263 return BinaryOperator::CreateOr(A, B);
2264
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002265 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2266 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2267 return BinaryOperator::CreateOr(Not, Op0);
2268 }
2269 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2270 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2271 return BinaryOperator::CreateOr(Not, Op0);
2272 }
2273 }
2274
2275 // A | ~(A | B) -> A | ~B
2276 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002277 if (match(Op1, m_Not(m_Value(A))))
2278 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002279 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2280 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2281 B->getOpcode() == Instruction::Xor)) {
2282 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2283 B->getOperand(0);
2284 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2285 return BinaryOperator::CreateOr(Not, Op0);
2286 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002287
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002288 // (A & B) | (~A ^ B) -> (~A ^ B)
2289 // (A & B) | (B ^ ~A) -> (~A ^ B)
2290 // (B & A) | (~A ^ B) -> (~A ^ B)
2291 // (B & A) | (B ^ ~A) -> (~A ^ B)
2292 // The match order is important: match the xor first because the 'not'
2293 // operation defines 'A'. We do not need to match the xor as Op0 because the
2294 // xor was canonicalized to Op1 above.
2295 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2296 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002297 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2298
Eli Friedmane06535b2012-03-16 00:52:42 +00002299 if (SwappedForXor)
2300 std::swap(Op0, Op1);
2301
David Majnemer3d6f80b2014-11-28 19:58:29 +00002302 {
2303 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2304 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2305 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002306 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002307 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002308
David Majnemer3d6f80b2014-11-28 19:58:29 +00002309 // TODO: Make this recursive; it's a little tricky because an arbitrary
2310 // number of 'or' instructions might have to be created.
2311 Value *X, *Y;
2312 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2313 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2314 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002315 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002316 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2317 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002318 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002319 }
2320 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2321 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2322 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002323 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002324 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2325 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002326 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002327 }
2328 }
2329
Chris Lattner4e8137d2010-02-11 06:26:33 +00002330 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2331 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2332 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002333 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002334 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002335
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002336 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2337 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002338
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002339 // 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 +00002340 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002341 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002342 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002343 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002344 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002345 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2346
Owen Andersonc237a842010-09-13 17:59:27 +00002347 // Note: If we've gotten to the point of visiting the outer OR, then the
2348 // inner one couldn't be simplified. If it was a constant, then it won't
2349 // be simplified by a later pass either, so we try swapping the inner/outer
2350 // ORs in the hopes that we'll be able to simplify it this way.
2351 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002352 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002353 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2354 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2355 Value *Inner = Builder->CreateOr(A, Op1);
2356 Inner->takeName(Op0);
2357 return BinaryOperator::CreateOr(Inner, C1);
2358 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002359
Bill Wendling23242092013-02-16 23:41:36 +00002360 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2361 // Since this OR statement hasn't been optimized further yet, we hope
2362 // that this transformation will allow the new ORs to be optimized.
2363 {
Craig Topperf40110f2014-04-25 05:29:35 +00002364 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002365 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2366 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2367 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2368 Value *orTrue = Builder->CreateOr(A, C);
2369 Value *orFalse = Builder->CreateOr(B, D);
2370 return SelectInst::Create(X, orTrue, orFalse);
2371 }
2372 }
2373
Craig Topperf40110f2014-04-25 05:29:35 +00002374 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002375}
2376
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002377// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2378// here. We should standardize that construct where it is needed or choose some
2379// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002380Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002381 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2383
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002384 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002385 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002386
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002387 if (Value *V = SimplifyXorInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002389
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002390 // (A&B)^(A&C) -> A&(B^C) etc
2391 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002392 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002393
Craig Topper9d4171a2012-12-20 07:09:41 +00002394 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002395 // purpose is to compute bits we don't care about.
2396 if (SimplifyDemandedInstructionBits(I))
2397 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002398
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002399 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002400 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002401
Sanjay Patel3b863f82017-04-22 18:05:35 +00002402 // Is this a 'not' (~) fed by a binary operator?
2403 BinaryOperator *NotOp;
2404 if (match(&I, m_Not(m_BinOp(NotOp)))) {
2405 if (NotOp->getOpcode() == Instruction::And ||
2406 NotOp->getOpcode() == Instruction::Or) {
2407 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2408 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2409 if (dyn_castNotVal(NotOp->getOperand(1)))
2410 NotOp->swapOperands();
2411 if (Value *Op0NotVal = dyn_castNotVal(NotOp->getOperand(0))) {
2412 Value *NotY = Builder->CreateNot(
2413 NotOp->getOperand(1), NotOp->getOperand(1)->getName() + ".not");
2414 if (NotOp->getOpcode() == Instruction::And)
2415 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2416 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002417 }
Sanjay Patel3b863f82017-04-22 18:05:35 +00002418
2419 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2420 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2421 if (IsFreeToInvert(NotOp->getOperand(0),
2422 NotOp->getOperand(0)->hasOneUse()) &&
2423 IsFreeToInvert(NotOp->getOperand(1),
2424 NotOp->getOperand(1)->hasOneUse())) {
2425 Value *NotX = Builder->CreateNot(NotOp->getOperand(0), "notlhs");
2426 Value *NotY = Builder->CreateNot(NotOp->getOperand(1), "notrhs");
2427 if (NotOp->getOpcode() == Instruction::And)
2428 return BinaryOperator::CreateOr(NotX, NotY);
2429 return BinaryOperator::CreateAnd(NotX, NotY);
2430 }
2431 } else if (NotOp->getOpcode() == Instruction::AShr) {
2432 // ~(~X >>s Y) --> (X >>s Y)
2433 if (Value *Op0NotVal = dyn_castNotVal(NotOp->getOperand(0)))
2434 return BinaryOperator::CreateAShr(Op0NotVal, NotOp->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002435 }
2436 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002437
Sanjay Patel33439f92017-04-12 15:11:33 +00002438 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2439 ICmpInst::Predicate Pred;
2440 if (match(Op0, m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))) &&
2441 match(Op1, m_AllOnes())) {
2442 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2443 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002444 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002445
Craig Topper9d1821b2017-04-09 06:12:31 +00002446 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002447 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2448 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2449 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2450 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2451 Instruction::CastOps Opcode = Op0C->getOpcode();
2452 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002453 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002454 Op0C->getDestTy()))) {
2455 CI->setPredicate(CI->getInversePredicate());
2456 return CastInst::Create(Opcode, CI, Op0C->getType());
2457 }
2458 }
2459 }
2460 }
2461
2462 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2463 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002464 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002465 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2466 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002467 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2468 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002469 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002470
Chris Lattner0a8191e2010-01-05 07:50:36 +00002471 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2472 if (Op0I->getOpcode() == Instruction::Add) {
2473 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002474 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002475 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002476 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2477 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002478 } else if (RHSC->getValue().isSignMask()) {
2479 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002480 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002481 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2482
2483 }
2484 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002485 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002486 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2487 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002488 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002489 // Anything in both C1 and C2 is known to be zero, remove it from
2490 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002491 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002492 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002493 ConstantExpr::getNot(CommonBits));
2494 Worklist.Add(Op0I);
2495 I.setOperand(0, Op0I->getOperand(0));
2496 I.setOperand(1, NewRHS);
2497 return &I;
2498 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002499 } else if (Op0I->getOpcode() == Instruction::LShr) {
2500 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2501 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002502 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002503 ConstantInt *C1;
2504 if (Op0I->hasOneUse() &&
2505 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2506 E1->getOpcode() == Instruction::Xor &&
2507 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2508 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002509 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002510 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2511 FoldConst ^= C3->getValue();
2512 // Prepare the two operands.
2513 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2514 Opnd0->takeName(Op0I);
2515 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2516 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2517
2518 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2519 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002520 }
2521 }
2522 }
Craig Topper86173602017-04-04 20:26:25 +00002523 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002524
Craig Topper86173602017-04-04 20:26:25 +00002525 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002526 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2527 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002528
Craig Topper76394602017-04-10 06:53:23 +00002529 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002530 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002531 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002532 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002533 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002534 std::swap(A, B);
2535 }
2536 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002537 I.swapOperands(); // Simplified below.
2538 std::swap(Op0, Op1);
2539 }
Craig Topper76394602017-04-10 06:53:23 +00002540 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002541 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002542 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002543 std::swap(A, B);
2544 }
2545 if (B == Op0) { // A^(B&A) -> (B&A)^A
2546 I.swapOperands(); // Simplified below.
2547 std::swap(Op0, Op1);
2548 }
2549 }
2550 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002551
Craig Topper76394602017-04-10 06:53:23 +00002552 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002553 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002554 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002555 if (A == Op1) // (B|A)^B == (A|B)^B
2556 std::swap(A, B);
2557 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002558 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002559 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002560 if (A == Op1) // (A&B)^A -> (B&A)^A
2561 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002562 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002563 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002564 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002565 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002566 }
2567 }
2568 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002569
Craig Topper76394602017-04-10 06:53:23 +00002570 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002571 Value *A, *B, *C, *D;
2572 // (A & B)^(A | B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002573 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2574 match(Op1, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002575 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002576 return BinaryOperator::CreateXor(A, B);
2577 }
2578 // (A | B)^(A & B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002579 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2580 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002581 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002582 return BinaryOperator::CreateXor(A, B);
2583 }
David Majnemer698dca02014-08-14 06:46:25 +00002584 // (A | ~B) ^ (~A | B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002585 // (~B | A) ^ (~A | B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002586 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2587 match(Op1, m_Or(m_Not(m_Specific(A)), m_Specific(B))))
David Majnemer698dca02014-08-14 06:46:25 +00002588 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002589
David Majnemer698dca02014-08-14 06:46:25 +00002590 // (~A | B) ^ (A | ~B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002591 if (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2592 match(Op1, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
David Majnemer698dca02014-08-14 06:46:25 +00002593 return BinaryOperator::CreateXor(A, B);
2594 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002595 // (A & ~B) ^ (~A & B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002596 // (~B & A) ^ (~A & B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002597 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2598 match(Op1, m_And(m_Not(m_Specific(A)), m_Specific(B))))
Mayur Pandey960507b2014-08-19 08:19:19 +00002599 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002600
Mayur Pandey960507b2014-08-19 08:19:19 +00002601 // (~A & B) ^ (A & ~B) -> A ^ B
Craig Topper76394602017-04-10 06:53:23 +00002602 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2603 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
Mayur Pandey960507b2014-08-19 08:19:19 +00002604 return BinaryOperator::CreateXor(A, B);
2605 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002606 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002607 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2608 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002609 if (D == A)
2610 return BinaryOperator::CreateXor(
2611 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2612 if (D == B)
2613 return BinaryOperator::CreateXor(
2614 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002615 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002616 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002617 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2618 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002619 if (D == A)
2620 return BinaryOperator::CreateXor(
2621 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2622 if (D == B)
2623 return BinaryOperator::CreateXor(
2624 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002625 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002626 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002627 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002628 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002629 return BinaryOperator::CreateOr(A, B);
2630 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002631 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002632 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002633 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002634 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002635
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002636 // (A & ~B) ^ ~A -> ~(A & B)
2637 // (~B & A) ^ ~A -> ~(A & B)
2638 Value *A, *B;
2639 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002640 match(Op1, m_Not(m_Specific(A))))
2641 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2642
David Majnemerb0761a02016-12-21 19:21:59 +00002643 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002644 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
David Majnemerb0761a02016-12-21 19:21:59 +00002645 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002646 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2647 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2648 LHS->getOperand(1) == RHS->getOperand(0))
2649 LHS->swapOperands();
2650 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2651 LHS->getOperand(1) == RHS->getOperand(1)) {
2652 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2653 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2654 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002655 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002656 getNewICmpValue(isSigned, Code, Op0, Op1,
2657 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002658 }
2659 }
2660
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002661 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2662 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002663
Craig Topperf40110f2014-04-25 05:29:35 +00002664 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002665}