blob: a81f295b91d4e787455ebb9869edfc6ff7bb8450 [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"
Craig Topper0aa3a192017-08-14 21:39:51 +000015#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000017#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000057 InstCombiner::BuilderTy &Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
Craig Topperbb4069e2017-07-07 23:16:26 +000061 return Builder.CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000067 InstCombiner::BuilderTy &Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Craig Topperbb4069e2017-07-07 23:16:26 +000075 return Builder.CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
Craig Topper95e41422017-07-06 16:24:23 +000083static Value *SimplifyBSwap(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +000084 InstCombiner::BuilderTy &Builder) {
Craig Topperc6948c22017-07-03 05:54:11 +000085 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86
Craig Topper22795de2017-07-06 16:24:21 +000087 Value *OldLHS = I.getOperand(0);
88 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000089
Craig Topper766ce6e2017-07-03 05:54:15 +000090 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000091 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000092 return nullptr;
93
Craig Topper766ce6e2017-07-03 05:54:15 +000094 Value *NewRHS;
95 const APInt *C;
96
Craig Topper22795de2017-07-06 16:24:21 +000097 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000098 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000099 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
100 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000102 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000103 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000104 if (!OldLHS->hasOneUse())
105 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000106 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
107 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000108 return nullptr;
109
Craig Topperbb4069e2017-07-07 23:16:26 +0000110 Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000111 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
112 I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000113 return Builder.CreateCall(F, BinOp);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000114}
115
Sanjay Patel18549272015-09-08 18:24:36 +0000116/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000117/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
118Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000119 ConstantInt *OpRHS,
120 ConstantInt *AndRHS,
121 BinaryOperator &TheAnd) {
122 Value *X = Op->getOperand(0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000123
124 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000125 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000126 case Instruction::Add:
127 if (Op->hasOneUse()) {
128 // Adding a one to a single bit bit-field should be turned into an XOR
129 // of the bit. First thing to check is to see if this AND is with a
130 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000131 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000132
133 // If there is only one bit set.
134 if (AndRHSV.isPowerOf2()) {
135 // Ok, at this point, we know that we are masking the result of the
136 // ADD down to exactly one bit. If the constant we are adding has
137 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000138 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000139
140 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000141 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142 // If not, the only thing that can effect the output of the AND is
143 // the bit specified by AndRHSV. If that bit is set, the effect of
144 // the XOR is to toggle the bit. If it is clear, then the ADD has
145 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000146 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000147 TheAnd.setOperand(0, X);
148 return &TheAnd;
149 } else {
150 // Pull the XOR out of the AND.
Craig Topperbb4069e2017-07-07 23:16:26 +0000151 Value *NewAnd = Builder.CreateAnd(X, AndRHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000152 NewAnd->takeName(Op);
153 return BinaryOperator::CreateXor(NewAnd, AndRHS);
154 }
155 }
156 }
157 }
158 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000159 }
Craig Topperf40110f2014-04-25 05:29:35 +0000160 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000161}
162
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000163/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000164/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
165/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000166Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000167 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000168 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000169 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000170
Sanjay Patel85d79742016-08-31 19:49:56 +0000171 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000172 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000173 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000175 // V >= Min && V < Hi --> V < Hi
176 // V < Min || V >= Hi --> V >= Hi
177 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000178 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000179 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Craig Topperbb4069e2017-07-07 23:16:26 +0000180 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181 }
182
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000183 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
184 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000185 Value *VMinusLo =
Craig Topperbb4069e2017-07-07 23:16:26 +0000186 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
Sanjay Patel85d79742016-08-31 19:49:56 +0000187 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Craig Topperbb4069e2017-07-07 23:16:26 +0000188 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000189}
190
Sanjay Patel77bf6222017-04-03 16:53:12 +0000191/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
192/// that can be simplified.
193/// One of A and B is considered the mask. The other is the value. This is
194/// described as the "AMask" or "BMask" part of the enum. If the enum contains
195/// only "Mask", then both A and B can be considered masks. If A is the mask,
196/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
197/// If both A and C are constants, this proof is also easy.
198/// For the following explanations, we assume that A is the mask.
199///
200/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
201/// bits of A are set in B.
202/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
203///
204/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
205/// bits of A are cleared in B.
206/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
207///
208/// "Mixed" declares that (A & B) == C and C might or might not contain any
209/// number of one bits and zero bits.
210/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
211///
212/// "Not" means that in above descriptions "==" should be replaced by "!=".
213/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
214///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000215/// If the mask A contains a single bit, then the following is equivalent:
216/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
217/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
218enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000219 AMask_AllOnes = 1,
220 AMask_NotAllOnes = 2,
221 BMask_AllOnes = 4,
222 BMask_NotAllOnes = 8,
223 Mask_AllZeros = 16,
224 Mask_NotAllZeros = 32,
225 AMask_Mixed = 64,
226 AMask_NotMixed = 128,
227 BMask_Mixed = 256,
228 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000229};
230
Sanjay Patel77bf6222017-04-03 16:53:12 +0000231/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
232/// satisfies.
233static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
234 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000235 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
236 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
237 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000238 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
239 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
240 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
241 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000242 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000243 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000244 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
245 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
246 if (IsAPow2)
247 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
248 : (AMask_AllOnes | AMask_Mixed));
249 if (IsBPow2)
250 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
251 : (BMask_AllOnes | BMask_Mixed));
252 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000253 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000254
Owen Anderson3fe002d2010-09-08 22:16:17 +0000255 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000256 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
257 : (AMask_NotAllOnes | AMask_NotMixed));
258 if (IsAPow2)
259 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
260 : (Mask_AllZeros | AMask_Mixed));
261 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
262 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000263 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000264
Craig Topperae48cb22012-12-20 07:15:54 +0000265 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000266 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
267 : (BMask_NotAllOnes | BMask_NotMixed));
268 if (IsBPow2)
269 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
270 : (Mask_AllZeros | BMask_Mixed));
271 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
272 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000273 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000274
275 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000276}
277
Tim Northoverc0756c42013-09-04 11:57:13 +0000278/// Convert an analysis of a masked ICmp into its equivalent if all boolean
279/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
280/// is adjacent to the corresponding normal flag (recording ==), this just
281/// involves swapping those bits over.
282static unsigned conjugateICmpMask(unsigned Mask) {
283 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000284 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
285 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000286 << 1;
287
Sanjay Patel77bf6222017-04-03 16:53:12 +0000288 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
289 AMask_NotMixed | BMask_NotMixed))
290 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000291
292 return NewMask;
293}
294
Craig Topper0aa3a192017-08-14 21:39:51 +0000295// Adapts the external decomposeBitTestICmp for local use.
296static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
297 Value *&X, Value *&Y, Value *&Z) {
298 APInt Mask;
299 if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
300 return false;
301
Craig Topper085c1f42017-09-01 21:27:29 +0000302 Y = ConstantInt::get(X->getType(), Mask);
303 Z = ConstantInt::get(X->getType(), 0);
Craig Topper0aa3a192017-08-14 21:39:51 +0000304 return true;
305}
306
Sanjay Patel77bf6222017-04-03 16:53:12 +0000307/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
308/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
309/// RHS satisfy.
310static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
311 Value *&D, Value *&E, ICmpInst *LHS,
312 ICmpInst *RHS,
313 ICmpInst::Predicate &PredL,
314 ICmpInst::Predicate &PredR) {
Craig Topper775ffcc2017-08-21 21:00:45 +0000315 // vectors are not (yet?) supported. Don't support pointers either.
Craig Topperd3b46562017-09-01 21:27:31 +0000316 if (!LHS->getOperand(0)->getType()->isIntegerTy() ||
317 !RHS->getOperand(0)->getType()->isIntegerTy())
Sanjay Patel77bf6222017-04-03 16:53:12 +0000318 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000319
320 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000321 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000322 // and L11 & L12 == L21 & L22. The same goes for RHS.
323 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000324 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000325 // above.
326 Value *L1 = LHS->getOperand(0);
327 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000328 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000329 // Check whether the icmp can be decomposed into a bit test.
Craig Topper0aa3a192017-08-14 21:39:51 +0000330 if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000331 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000332 } else {
333 // Look for ANDs in the LHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000334 if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000335 // Any icmp can be viewed as being trivially masked; if it allows us to
336 // remove one, it's worth it.
337 L11 = L1;
338 L12 = Constant::getAllOnesValue(L1->getType());
339 }
340
Craig Topper775ffcc2017-08-21 21:00:45 +0000341 if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000342 L21 = L2;
343 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000344 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000346
347 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000349 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000350
351 Value *R1 = RHS->getOperand(0);
352 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000353 Value *R11, *R12;
354 bool Ok = false;
Craig Topper0aa3a192017-08-14 21:39:51 +0000355 if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000356 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000357 A = R11;
358 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000359 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000360 A = R12;
361 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000362 } else {
363 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000364 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000365 E = R2;
366 R1 = nullptr;
367 Ok = true;
Craig Topper775ffcc2017-08-21 21:00:45 +0000368 } else {
Tim Northoverdc647a22013-09-04 11:57:17 +0000369 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
370 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000371 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000372 R11 = R1;
373 R12 = Constant::getAllOnesValue(R1->getType());
374 }
375
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000376 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000377 A = R11;
378 D = R12;
379 E = R2;
380 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000381 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000382 A = R12;
383 D = R11;
384 E = R2;
385 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000386 }
387 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000388
389 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000390 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000391 return 0;
392
Chad Rosier58919cc2016-05-09 21:37:43 +0000393 // Look for ANDs on the right side of the RHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000394 if (!Ok) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000395 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
396 R11 = R2;
397 R12 = Constant::getAllOnesValue(R2->getType());
398 }
399
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000400 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000401 A = R11;
402 D = R12;
403 E = R1;
404 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000405 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000406 A = R12;
407 D = R11;
408 E = R1;
409 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000410 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000411 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000412 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000413 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000414 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415 return 0;
416
417 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000418 B = L12;
419 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000420 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000421 B = L11;
422 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000423 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000424 B = L22;
425 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000426 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000427 B = L21;
428 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429 }
430
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
432 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000433 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000434}
Sanjay Patel18549272015-09-08 18:24:36 +0000435
436/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
437/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000438static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000439 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000440 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000441 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
442 unsigned Mask =
443 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
444 if (Mask == 0)
445 return nullptr;
446
447 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
448 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000449
Tim Northoverc0756c42013-09-04 11:57:13 +0000450 // In full generality:
451 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
452 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
453 //
454 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
455 // equivalent to (icmp (A & X) !Op Y).
456 //
457 // Therefore, we can pretend for the rest of this function that we're dealing
458 // with the conjunction, provided we flip the sense of any comparisons (both
459 // input and output).
460
461 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000462 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000463 if (!IsAnd) {
464 // Convert the masking analysis into its equivalent with negated
465 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000466 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000467 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000468
Sanjay Patel77bf6222017-04-03 16:53:12 +0000469 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000470 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000471 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000472 Value *NewOr = Builder.CreateOr(B, D);
473 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000474 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000475 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000476 // with B and D, having a single bit set.
477 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000478 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000479 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000480 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000481 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000482 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000483 Value *NewOr = Builder.CreateOr(B, D);
484 Value *NewAnd = Builder.CreateAnd(A, NewOr);
485 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000486 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000487 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000488 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000489 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000490 Value *NewAnd1 = Builder.CreateAnd(B, D);
491 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
492 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000493 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000494
495 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000496 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000497 // easy cases for now" decision.
498 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000499 if (!BCst)
500 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000501 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000502 if (!DCst)
503 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000504
Sanjay Patel77bf6222017-04-03 16:53:12 +0000505 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000506 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
507 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
508 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
509 // Only valid if one of the masks is a superset of the other (check "B&D" is
510 // the same as either B or D).
511 APInt NewMask = BCst->getValue() & DCst->getValue();
512
513 if (NewMask == BCst->getValue())
514 return LHS;
515 else if (NewMask == DCst->getValue())
516 return RHS;
517 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000518
519 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000520 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
521 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
522 // Only valid if one of the masks is a superset of the other (check "B|D" is
523 // the same as either B or D).
524 APInt NewMask = BCst->getValue() | DCst->getValue();
525
526 if (NewMask == BCst->getValue())
527 return LHS;
528 else if (NewMask == DCst->getValue())
529 return RHS;
530 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000531
532 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000533 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000534 // We already know that B & C == C && D & E == E.
535 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
536 // C and E, which are shared by both the mask B and the mask D, don't
537 // contradict, then we can transform to
538 // -> (icmp eq (A & (B|D)), (C|E))
539 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000540 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000541 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000542 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000543 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000544 if (!CCst)
545 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000546 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000547 if (!ECst)
548 return nullptr;
549 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000550 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000551 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000552 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000553
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000554 // If there is a conflict, we should actually return a false for the
555 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000556 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000557 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000558 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000559
Craig Topperbb4069e2017-07-07 23:16:26 +0000560 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000561 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000562 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
563 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000565
Craig Topperf40110f2014-04-25 05:29:35 +0000566 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000567}
568
Erik Ecksteind1817522014-12-03 10:39:15 +0000569/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
570/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
571/// If \p Inverted is true then the check is for the inverted range, e.g.
572/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
573Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
574 bool Inverted) {
575 // Check the lower range comparison, e.g. x >= 0
576 // InstCombine already ensured that if there is a constant it's on the RHS.
577 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
578 if (!RangeStart)
579 return nullptr;
580
581 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
582 Cmp0->getPredicate());
583
584 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
585 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
586 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
587 return nullptr;
588
589 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
590 Cmp1->getPredicate());
591
592 Value *Input = Cmp0->getOperand(0);
593 Value *RangeEnd;
594 if (Cmp1->getOperand(0) == Input) {
595 // For the upper range compare we have: icmp x, n
596 RangeEnd = Cmp1->getOperand(1);
597 } else if (Cmp1->getOperand(1) == Input) {
598 // For the upper range compare we have: icmp n, x
599 RangeEnd = Cmp1->getOperand(0);
600 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
601 } else {
602 return nullptr;
603 }
604
605 // Check the upper range comparison, e.g. x < n
606 ICmpInst::Predicate NewPred;
607 switch (Pred1) {
608 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
609 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
610 default: return nullptr;
611 }
612
613 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000614 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
615 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000616 return nullptr;
617
618 if (Inverted)
619 NewPred = ICmpInst::getInversePredicate(NewPred);
620
Craig Topperbb4069e2017-07-07 23:16:26 +0000621 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000622}
623
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000624static Value *
625foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
626 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000627 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000628 Value *X = LHS->getOperand(0);
629 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000630 return nullptr;
631
Sanjay Patelef9f5862017-04-15 17:55:06 +0000632 const APInt *C1, *C2;
633 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
634 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000635 return nullptr;
636
637 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
638 ICmpInst::Predicate Pred = LHS->getPredicate();
639 if (Pred != RHS->getPredicate())
640 return nullptr;
641 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
642 return nullptr;
643 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
644 return nullptr;
645
646 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000647 if (C1->ugt(*C2))
648 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000649
Sanjay Patelef9f5862017-04-15 17:55:06 +0000650 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000651 if (Xor.isPowerOf2()) {
652 // If LHSC and RHSC differ by only one bit, then set that bit in X and
653 // compare against the larger constant:
654 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
655 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
656 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
657 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000658 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
659 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000660 }
661
662 // Special case: get the ordering right when the values wrap around zero.
663 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000664 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000665 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000666
Sanjay Patelef9f5862017-04-15 17:55:06 +0000667 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000668 // (X == 13 || X == 14) --> X - 13 <=u 1
669 // (X != 13 && X != 14) --> X - 13 >u 1
670 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000671 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000672 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000673 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000674 }
675
676 return nullptr;
677}
678
Craig Topperda6ea0d2017-06-16 05:10:37 +0000679// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
680// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
681Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
682 bool JoinedByAnd,
683 Instruction &CxtI) {
684 ICmpInst::Predicate Pred = LHS->getPredicate();
685 if (Pred != RHS->getPredicate())
686 return nullptr;
687 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
688 return nullptr;
689 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
690 return nullptr;
691
692 // TODO support vector splats
693 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
694 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
695 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
696 return nullptr;
697
698 Value *A, *B, *C, *D;
699 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
700 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
701 if (A == D || B == D)
702 std::swap(C, D);
703 if (B == C)
704 std::swap(A, B);
705
706 if (A == C &&
707 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
708 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000709 Value *Mask = Builder.CreateOr(B, D);
710 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000711 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000712 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000713 }
714 }
715
716 return nullptr;
717}
718
Sanjay Patel18549272015-09-08 18:24:36 +0000719/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000720Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
721 Instruction &CxtI) {
722 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
723 // if K1 and K2 are a one-bit mask.
724 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
725 return V;
726
Sanjay Patel519a87a2017-04-05 17:38:34 +0000727 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000728
729 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000730 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000731 if (LHS->getOperand(0) == RHS->getOperand(1) &&
732 LHS->getOperand(1) == RHS->getOperand(0))
733 LHS->swapOperands();
734 if (LHS->getOperand(0) == RHS->getOperand(0) &&
735 LHS->getOperand(1) == RHS->getOperand(1)) {
736 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
737 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
738 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000739 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000740 }
741 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000742
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000743 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000744 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000745 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000746
Erik Ecksteind1817522014-12-03 10:39:15 +0000747 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
748 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
749 return V;
750
751 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
752 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
753 return V;
754
Sanjay Patelef9f5862017-04-15 17:55:06 +0000755 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
756 return V;
757
Chris Lattner0a8191e2010-01-05 07:50:36 +0000758 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000759 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000760 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
761 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
762 if (!LHSC || !RHSC)
763 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000764
Sanjay Patel519a87a2017-04-05 17:38:34 +0000765 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000766 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000767 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000768 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000769 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
770 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000771 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
772 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000773 }
774 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000775
Benjamin Kramer101720f2011-04-28 20:09:57 +0000776 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000777 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000778 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000779 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
780 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000781 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000782 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000783
784 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000785 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000786 if (match(RHS0, m_Trunc(m_Value(V))) &&
787 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000788 SmallC = RHSC;
789 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000790 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
791 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000792 SmallC = LHSC;
793 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000794 }
795
Sanjay Patel519a87a2017-04-05 17:38:34 +0000796 if (SmallC && BigC) {
797 unsigned BigBitSize = BigC->getType()->getBitWidth();
798 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000799
800 // Check that the low bits are zero.
801 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000802 if ((Low & AndC->getValue()).isNullValue() &&
803 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000804 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +0000805 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
806 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +0000807 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000808 }
809 }
810 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000811
Chris Lattner0a8191e2010-01-05 07:50:36 +0000812 // From here on, we only handle:
813 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000814 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000815 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000816
Sanjay Patel519a87a2017-04-05 17:38:34 +0000817 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
818 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
819 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
820 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
821 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000823
Chris Lattner0a8191e2010-01-05 07:50:36 +0000824 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000825 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000826 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000827
Chris Lattner0a8191e2010-01-05 07:50:36 +0000828 // Ensure that the larger constant is on the RHS.
829 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000830 if (CmpInst::isSigned(PredL) ||
831 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000832 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000833 else
834 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000835
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 if (ShouldSwap) {
837 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000838 std::swap(LHSC, RHSC);
839 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000840 }
841
Dan Gohman4a618822010-02-10 16:03:48 +0000842 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000843 // comparing a value against two constants and and'ing the result
844 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000845 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
846 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000847 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000848 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000849
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 switch (PredL) {
851 default:
852 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000853 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000854 switch (PredR) {
855 default:
856 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000857 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000858 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000859 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000860 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000861 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000862 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000863 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000864 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000865 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000866 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000868 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000869 // Potential folds for this case should already be handled.
870 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000871 }
872 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000873 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000874 switch (PredR) {
875 default:
876 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000877 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000878 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000879 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000880 break; // (X u> 13 & X != 15) -> no change
881 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000882 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
883 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 }
885 break;
886 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000887 switch (PredR) {
888 default:
889 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000890 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000891 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000892 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000893 break; // (X s> 13 & X != 15) -> no change
894 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000895 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000896 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 }
898 break;
899 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000900
Craig Topperf40110f2014-04-25 05:29:35 +0000901 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000902}
903
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000904Value *InstCombiner::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
Sanjay Patel275bb5a2017-09-02 17:17:17 +0000905 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
906 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
907 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Tim Shenaec68b22016-06-29 20:10:17 +0000908
Sanjay Patel275bb5a2017-09-02 17:17:17 +0000909 if (LHS0 == RHS1 && RHS0 == LHS1) {
Tim Shenaec68b22016-06-29 20:10:17 +0000910 // Swap RHS operands to match LHS.
Sanjay Patel275bb5a2017-09-02 17:17:17 +0000911 PredR = FCmpInst::getSwappedPredicate(PredR);
912 std::swap(RHS0, RHS1);
Tim Shenaec68b22016-06-29 20:10:17 +0000913 }
914
915 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
916 // Suppose the relation between x and y is R, where R is one of
917 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
918 // testing the desired relations.
919 //
920 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
921 // bool(R & CC0) && bool(R & CC1)
922 // = bool((R & CC0) & (R & CC1))
923 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
Sanjay Patel4c52f762017-09-02 16:30:27 +0000924 //
925 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
926 // bool(R & CC0) || bool(R & CC1)
927 // = bool((R & CC0) | (R & CC1))
928 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000929 if (LHS0 == RHS0 && LHS1 == RHS1) {
930 unsigned FCmpCodeL = getFCmpCode(PredL);
931 unsigned FCmpCodeR = getFCmpCode(PredR);
932 unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
933 return getFCmpValue(NewPred, LHS0, LHS1, Builder);
934 }
Sanjay Patel4c52f762017-09-02 16:30:27 +0000935
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000936 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
937 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
Sanjay Patel275bb5a2017-09-02 17:17:17 +0000938 if (LHS0->getType() != RHS0->getType())
939 return nullptr;
940
Sanjay Patel6840c5f2017-09-05 23:13:13 +0000941 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
942 // (fcmp ord/uno X, C) will be transformed to (fcmp X, 0.0).
943 if (match(LHS1, m_Zero()) && LHS1 == RHS1)
944 // Ignore the constants because they are obviously not NANs:
945 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
946 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000947 return Builder.CreateFCmp(PredL, LHS0, RHS0);
Sanjay Patel4c52f762017-09-02 16:30:27 +0000948 }
949
950 return nullptr;
951}
952
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000953/// Match De Morgan's Laws:
954/// (~A & ~B) == (~(A | B))
955/// (~A | ~B) == (~(A & B))
956static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +0000957 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000958 auto Opcode = I.getOpcode();
959 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
960 "Trying to match De Morgan's Laws with something other than and/or");
961
Sanjay Patel7caaa792017-05-09 20:05:05 +0000962 // Flip the logic operation.
963 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
964
965 Value *A, *B;
966 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
967 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
968 !IsFreeToInvert(A, A->hasOneUse()) &&
969 !IsFreeToInvert(B, B->hasOneUse())) {
970 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
971 return BinaryOperator::CreateNot(AndOr);
972 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000973
974 return nullptr;
975}
976
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000977bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
978 Value *CastSrc = CI->getOperand(0);
979
980 // Noop casts and casts of constants should be eliminated trivially.
981 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
982 return false;
983
984 // If this cast is paired with another cast that can be eliminated, we prefer
985 // to have it eliminated.
986 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
987 if (isEliminableCastPair(PrecedingCI, CI))
988 return false;
989
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000990 return true;
991}
992
Sanjay Patel60312bc42016-09-12 00:16:23 +0000993/// Fold {and,or,xor} (cast X), C.
994static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +0000995 InstCombiner::BuilderTy &Builder) {
Craig Topper5706c012017-08-09 06:17:48 +0000996 Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
997 if (!C)
Sanjay Patel60312bc42016-09-12 00:16:23 +0000998 return nullptr;
999
1000 auto LogicOpc = Logic.getOpcode();
1001 Type *DestTy = Logic.getType();
1002 Type *SrcTy = Cast->getSrcTy();
1003
Craig Topperae9b87d2017-08-02 20:25:56 +00001004 // Move the logic operation ahead of a zext or sext if the constant is
1005 // unchanged in the smaller source type. Performing the logic in a smaller
1006 // type may provide more information to later folds, and the smaller logic
1007 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001008 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001009 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1010 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1011 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1012 if (ZextTruncC == C) {
1013 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001014 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001015 return new ZExtInst(NewOp, DestTy);
1016 }
1017 }
1018
Craig Topperae9b87d2017-08-02 20:25:56 +00001019 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1020 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1021 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1022 if (SextTruncC == C) {
1023 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1024 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1025 return new SExtInst(NewOp, DestTy);
1026 }
1027 }
1028
Sanjay Patel60312bc42016-09-12 00:16:23 +00001029 return nullptr;
1030}
1031
1032/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001033Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001034 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001035 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001036
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001038 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001039 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001040 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001041
Sanjay Patel9bba7502016-03-03 19:19:04 +00001042 // This must be a cast from an integer or integer vector source type to allow
1043 // transformation of the logic operation to the source type.
1044 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001045 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001046 if (!SrcTy->isIntOrIntVectorTy())
1047 return nullptr;
1048
Sanjay Patel60312bc42016-09-12 00:16:23 +00001049 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1050 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001051
Sanjay Patel9bba7502016-03-03 19:19:04 +00001052 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1053 if (!Cast1)
1054 return nullptr;
1055
1056 // Both operands of the logic operation are casts. The casts must be of the
1057 // same type for reduction.
1058 auto CastOpcode = Cast0->getOpcode();
1059 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001060 return nullptr;
1061
1062 Value *Cast0Src = Cast0->getOperand(0);
1063 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001064
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001065 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001066 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001067 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001068 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001069 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001070 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001071
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001072 // For now, only 'and'/'or' have optimizations after this.
1073 if (LogicOpc == Instruction::Xor)
1074 return nullptr;
1075
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001076 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001077 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001078 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1079 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1080 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001081 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001082 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001083 if (Res)
1084 return CastInst::Create(CastOpcode, Res, DestTy);
1085 return nullptr;
1086 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001087
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001088 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001089 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001090 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1091 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001092 if (FCmp0 && FCmp1)
1093 if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1094 return CastInst::Create(CastOpcode, R, DestTy);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001095
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001096 return nullptr;
1097}
1098
Sanjay Patele0c26e02017-04-23 22:00:02 +00001099static Instruction *foldAndToXor(BinaryOperator &I,
1100 InstCombiner::BuilderTy &Builder) {
1101 assert(I.getOpcode() == Instruction::And);
1102 Value *Op0 = I.getOperand(0);
1103 Value *Op1 = I.getOperand(1);
1104 Value *A, *B;
1105
1106 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1107 // (A | B) & ~(A & B) --> A ^ B
1108 // (A | B) & ~(B & A) --> A ^ B
1109 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1110 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1111 return BinaryOperator::CreateXor(A, B);
1112
1113 // (A | ~B) & (~A | B) --> ~(A ^ B)
1114 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1115 // (~B | A) & (~A | B) --> ~(A ^ B)
1116 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001117 if (Op0->hasOneUse() || Op1->hasOneUse())
1118 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1119 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1120 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001121
1122 return nullptr;
1123}
1124
1125static Instruction *foldOrToXor(BinaryOperator &I,
1126 InstCombiner::BuilderTy &Builder) {
1127 assert(I.getOpcode() == Instruction::Or);
1128 Value *Op0 = I.getOperand(0);
1129 Value *Op1 = I.getOperand(1);
1130 Value *A, *B;
1131
1132 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1133 // (A & B) | ~(A | B) --> ~(A ^ B)
1134 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001135 if (Op0->hasOneUse() || Op1->hasOneUse())
1136 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1137 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1138 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001139
1140 // (A & ~B) | (~A & B) --> A ^ B
1141 // (A & ~B) | (B & ~A) --> A ^ B
1142 // (~B & A) | (~A & B) --> A ^ B
1143 // (~B & A) | (B & ~A) --> A ^ B
1144 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1145 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1146 return BinaryOperator::CreateXor(A, B);
1147
1148 return nullptr;
1149}
1150
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001151// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1152// here. We should standardize that construct where it is needed or choose some
1153// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001154Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001155 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1157
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001158 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001159 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001160
Craig Toppera4205622017-06-09 03:21:29 +00001161 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001162 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001163
Craig Topper9d4171a2012-12-20 07:09:41 +00001164 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165 // purpose is to compute bits we don't care about.
1166 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001167 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001168
Sanjay Patele0c26e02017-04-23 22:00:02 +00001169 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001170 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001171 return Xor;
1172
1173 // (A|B)&(A|C) -> A|(B&C) etc
1174 if (Value *V = SimplifyUsingDistributiveLaws(I))
1175 return replaceInstUsesWith(I, V);
1176
Craig Topper95e41422017-07-06 16:24:23 +00001177 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001178 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001179
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001180 const APInt *C;
1181 if (match(Op1, m_APInt(C))) {
1182 Value *X, *Y;
1183 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1184 C->isOneValue()) {
1185 // (1 << X) & 1 --> zext(X == 0)
1186 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001187 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1188 return new ZExtInst(IsZero, I.getType());
1189 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001190
Craig Toppera1693a22017-08-06 23:11:49 +00001191 const APInt *XorC;
1192 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1193 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1194 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1195 Value *And = Builder.CreateAnd(X, Op1);
1196 And->takeName(Op0);
1197 return BinaryOperator::CreateXor(And, NewC);
1198 }
1199
Craig Topper7091a742017-08-07 18:10:39 +00001200 const APInt *OrC;
1201 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1202 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1203 // NOTE: This reduces the number of bits set in the & mask, which
1204 // can expose opportunities for store narrowing for scalars.
1205 // NOTE: SimplifyDemandedBits should have already removed bits from C1
1206 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1207 // above, but this feels safer.
1208 APInt Together = *C & *OrC;
1209 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(),
1210 Together ^ *C));
1211 And->takeName(Op0);
1212 return BinaryOperator::CreateOr(And, ConstantInt::get(I.getType(),
1213 Together));
1214 }
1215
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001216 // If the mask is only needed on one incoming arm, push the 'and' op up.
1217 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1218 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1219 APInt NotAndMask(~(*C));
1220 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1221 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1222 // Not masking anything out for the LHS, move mask to RHS.
1223 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1224 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1225 return BinaryOperator::Create(BinOp, X, NewRHS);
1226 }
1227 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1228 // Not masking anything out for the RHS, move mask to LHS.
1229 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1230 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1231 return BinaryOperator::Create(BinOp, NewLHS, Y);
1232 }
1233 }
Craig Toppera1693a22017-08-06 23:11:49 +00001234
Sanjay Patel3437ee22017-07-15 17:26:01 +00001235 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001236
Chris Lattner0a8191e2010-01-05 07:50:36 +00001237 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1238 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001239
1240 // Optimize a variety of ((val OP C1) & C2) combinations...
1241 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001242 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1243 // of X and OP behaves well when given trunc(C1) and X.
1244 switch (Op0I->getOpcode()) {
1245 default:
1246 break;
1247 case Instruction::Xor:
1248 case Instruction::Or:
1249 case Instruction::Mul:
1250 case Instruction::Add:
1251 case Instruction::Sub:
1252 Value *X;
1253 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001254 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001255 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1256 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1257 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001258 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001259 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001260 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001261 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001262 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001263 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001264 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001265 return new ZExtInst(And, I.getType());
1266 }
1267 }
1268 }
1269
Chris Lattner0a8191e2010-01-05 07:50:36 +00001270 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1271 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1272 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001273 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001274
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001275 // If this is an integer truncation, and if the source is an 'and' with
1276 // immediate, transform it. This frequently occurs for bitfield accesses.
1277 {
Craig Topperf40110f2014-04-25 05:29:35 +00001278 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001279 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1280 // Change: and (trunc (and X, YC) to T), C2
1281 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001282 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001283 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001284 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001285 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1286 C3 = ConstantExpr::getAnd(C3, AndRHS);
1287 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288 }
1289 }
Craig Topper86173602017-04-04 20:26:25 +00001290 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001291
Craig Topper86173602017-04-04 20:26:25 +00001292 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001293 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1294 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001295
Craig Topperbb4069e2017-07-07 23:16:26 +00001296 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001297 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001298
Chris Lattner0a8191e2010-01-05 07:50:36 +00001299 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001300 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001301 // A&(A^B) => A & ~B
1302 {
1303 Value *tmpOp0 = Op0;
1304 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001305 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001306 if (A == Op1 || B == Op1 ) {
1307 tmpOp1 = Op0;
1308 tmpOp0 = Op1;
1309 // Simplify below
1310 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001311 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001312
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001313 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001314 if (B == tmpOp0) {
1315 std::swap(A, B);
1316 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001317 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001318 // A is originally -1 (or a vector of -1 and undefs), then we enter
1319 // an endless loop. By checking that A is non-constant we ensure that
1320 // we will never get to the loop.
1321 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00001322 return BinaryOperator::CreateAnd(A, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001323 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001324 }
1325
David Majnemer42af3602014-07-30 21:26:37 +00001326 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1327 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1328 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001329 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001330 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001331
1332 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1333 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1334 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001335 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001336 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001337
1338 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001339 // (A | B) & (B ^ (~A)) -> (A & B)
1340 // (B | A) & ((~A) ^ B) -> (A & B)
1341 // (B | A) & (B ^ (~A)) -> (A & B)
1342 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1343 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001344 return BinaryOperator::CreateAnd(A, B);
1345
1346 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001347 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001348 // (B ^ (~A)) & (A | B) -> (A & B)
1349 // (B ^ (~A)) & (B | A) -> (A & B)
1350 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001351 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001352 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001353 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001354
David Majnemer5e96f1b2014-08-30 06:18:20 +00001355 {
1356 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1357 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1358 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001359 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001360 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001361
David Majnemer5e96f1b2014-08-30 06:18:20 +00001362 // TODO: Make this recursive; it's a little tricky because an arbitrary
1363 // number of 'and' instructions might have to be created.
1364 Value *X, *Y;
1365 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1366 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001367 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001368 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001369 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001370 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001371 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001372 }
1373 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1374 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001375 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001376 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001377 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001378 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001379 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001380 }
1381 }
1382
Chris Lattner4e8137d2010-02-11 06:26:33 +00001383 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1384 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001385 if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00001386 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001387
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001388 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1389 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001390
Craig Topper760ff6e2017-08-04 16:07:20 +00001391 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1392 Value *A;
1393 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1394 A->getType()->isIntOrIntVectorTy(1))
1395 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1396 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1397 A->getType()->isIntOrIntVectorTy(1))
1398 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001399
Craig Topperf40110f2014-04-25 05:29:35 +00001400 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001401}
1402
Chad Rosiera00df492016-05-25 16:22:14 +00001403/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1404/// insert the new intrinsic and return it.
1405Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001406 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1407
1408 // Look through zero extends.
1409 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1410 Op0 = Ext->getOperand(0);
1411
1412 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1413 Op1 = Ext->getOperand(0);
1414
1415 // (A | B) | C and A | (B | C) -> bswap if possible.
1416 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1417 match(Op1, m_Or(m_Value(), m_Value()));
1418
1419 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1420 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1421 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1422
1423 // (A & B) | (C & D) -> bswap if possible.
1424 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1425 match(Op1, m_And(m_Value(), m_Value()));
1426
1427 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1428 return nullptr;
1429
James Molloyf01488e2016-01-15 09:20:19 +00001430 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001431 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001432 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001433 Instruction *LastInst = Insts.pop_back_val();
1434 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001435
James Molloyf01488e2016-01-15 09:20:19 +00001436 for (auto *Inst : Insts)
1437 Worklist.Add(Inst);
1438 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001439}
1440
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001441/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1442static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1443 unsigned NumElts = C1->getType()->getVectorNumElements();
1444 for (unsigned i = 0; i != NumElts; ++i) {
1445 Constant *EltC1 = C1->getAggregateElement(i);
1446 Constant *EltC2 = C2->getAggregateElement(i);
1447 if (!EltC1 || !EltC2)
1448 return false;
1449
1450 // One element must be all ones, and the other must be all zeros.
1451 // FIXME: Allow undef elements.
1452 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1453 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1454 return false;
1455 }
1456 return true;
1457}
1458
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001459/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1460/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1461/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001462static Value *getSelectCondition(Value *A, Value *B,
1463 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001464 // If these are scalars or vectors of i1, A can be used directly.
1465 Type *Ty = A->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001466 if (match(A, m_Not(m_Specific(B))) && Ty->isIntOrIntVectorTy(1))
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001467 return A;
1468
1469 // If A and B are sign-extended, look through the sexts to find the booleans.
1470 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001471 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001472 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001473 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001474 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1475 NotB = peekThroughBitcast(NotB, true);
1476 if (match(NotB, m_SExt(m_Specific(Cond))))
1477 return Cond;
1478 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001479
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001480 // All scalar (and most vector) possibilities should be handled now.
1481 // Try more matches that only apply to non-splat constant vectors.
1482 if (!Ty->isVectorTy())
1483 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001484
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001485 // If both operands are constants, see if the constants are inverse bitmasks.
1486 Constant *AC, *BC;
1487 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
Craig Topper57b4d862017-08-10 17:48:14 +00001488 areInverseVectorBitmasks(AC, BC)) {
1489 return Builder.CreateZExtOrTrunc(AC, CmpInst::makeCmpResultType(Ty));
1490 }
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001491
1492 // If both operands are xor'd with constants using the same sexted boolean
1493 // operand, see if the constants are inverse bitmasks.
1494 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1495 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001496 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001497 areInverseVectorBitmasks(AC, BC)) {
1498 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1499 return Builder.CreateXor(Cond, AC);
1500 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001501 return nullptr;
1502}
1503
1504/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1505/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001506static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001507 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001508 // The potential condition of the select may be bitcasted. In that case, look
1509 // through its bitcast and the corresponding bitcast of the 'not' condition.
1510 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001511 A = peekThroughBitcast(A, true);
1512 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001513
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001514 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001515 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001516 // The bitcasts will either all exist or all not exist. The builder will
1517 // not create unnecessary casts if the types already match.
1518 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1519 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1520 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1521 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001522 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001523
Craig Topperf40110f2014-04-25 05:29:35 +00001524 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001525}
1526
Sanjay Patel18549272015-09-08 18:24:36 +00001527/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001528Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001529 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001530 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1531 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001532 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1533 return V;
1534
1535 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1536
Sanjay Patel519a87a2017-04-05 17:38:34 +00001537 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1538 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001539
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001540 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1541 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1542 // The original condition actually refers to the following two ranges:
1543 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1544 // We can fold these two ranges if:
1545 // 1) C1 and C2 is unsigned greater than C3.
1546 // 2) The two ranges are separated.
1547 // 3) C1 ^ C2 is one-bit mask.
1548 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1549 // This implies all values in the two ranges differ by exactly one bit.
1550
Sanjay Patel519a87a2017-04-05 17:38:34 +00001551 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1552 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1553 LHSC->getType() == RHSC->getType() &&
1554 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001555
1556 Value *LAdd = LHS->getOperand(0);
1557 Value *RAdd = RHS->getOperand(0);
1558
1559 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001560 ConstantInt *LAddC, *RAddC;
1561 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1562 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1563 LAddC->getValue().ugt(LHSC->getValue()) &&
1564 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001565
Sanjay Patel519a87a2017-04-05 17:38:34 +00001566 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1567 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1568 ConstantInt *MaxAddC = nullptr;
1569 if (LAddC->getValue().ult(RAddC->getValue()))
1570 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001571 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001572 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001573
Sanjay Patel519a87a2017-04-05 17:38:34 +00001574 APInt RRangeLow = -RAddC->getValue();
1575 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1576 APInt LRangeLow = -LAddC->getValue();
1577 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001578 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1579 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1580 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1581 : RRangeLow - LRangeLow;
1582
1583 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001584 RangeDiff.ugt(LHSC->getValue())) {
1585 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001586
Craig Topperbb4069e2017-07-07 23:16:26 +00001587 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1588 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1589 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001590 }
1591 }
1592 }
1593 }
1594
Chris Lattner0a8191e2010-01-05 07:50:36 +00001595 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001596 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001597 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1598 LHS->getOperand(1) == RHS->getOperand(0))
1599 LHS->swapOperands();
1600 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1601 LHS->getOperand(1) == RHS->getOperand(1)) {
1602 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1603 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1604 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001605 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001606 }
1607 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001608
1609 // handle (roughly):
1610 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001611 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001612 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001613
Sanjay Patele4159d22017-04-10 19:38:36 +00001614 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001615 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1616 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1617 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001618 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001619 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001620 B = LHS0;
1621 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1622 A = RHS0;
1623 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001624 A = RHS->getOperand(1);
1625 }
1626 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1627 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001628 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001629 B = RHS0;
1630 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1631 A = LHS0;
1632 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001633 A = LHS->getOperand(1);
1634 }
1635 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00001636 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00001637 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00001638 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00001639 }
1640
Erik Ecksteind1817522014-12-03 10:39:15 +00001641 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1642 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1643 return V;
1644
1645 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1646 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1647 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001648
Sanjay Patelef9f5862017-04-15 17:55:06 +00001649 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1650 return V;
1651
David Majnemerc2a990b2013-07-05 00:31:17 +00001652 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001653 if (!LHSC || !RHSC)
1654 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001655
Sanjay Patel519a87a2017-04-05 17:38:34 +00001656 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001657 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001658 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001659 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1660 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001661 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001662 }
1663
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001664 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001665 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001666 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1667 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001668 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001669 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001670 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001671 }
1672
Chris Lattner0a8191e2010-01-05 07:50:36 +00001673 // From here on, we only handle:
1674 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001675 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001676 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001677
Sanjay Patel519a87a2017-04-05 17:38:34 +00001678 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1679 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1680 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1681 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1682 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001683 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001684
Chris Lattner0a8191e2010-01-05 07:50:36 +00001685 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001686 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001687 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001688
Chris Lattner0a8191e2010-01-05 07:50:36 +00001689 // Ensure that the larger constant is on the RHS.
1690 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001691 if (CmpInst::isSigned(PredL) ||
1692 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001693 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001694 else
1695 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001696
Chris Lattner0a8191e2010-01-05 07:50:36 +00001697 if (ShouldSwap) {
1698 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001699 std::swap(LHSC, RHSC);
1700 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001701 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001702
Dan Gohman4a618822010-02-10 16:03:48 +00001703 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001704 // comparing a value against two constants and or'ing the result
1705 // together. Because of the above check, we know that we only have
1706 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1707 // icmp folding check above), that the two constants are not
1708 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001709 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001710
Sanjay Patel519a87a2017-04-05 17:38:34 +00001711 switch (PredL) {
1712 default:
1713 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001714 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001715 switch (PredR) {
1716 default:
1717 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001718 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001719 // Potential folds for this case should already be handled.
1720 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001721 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1722 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001723 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001724 }
1725 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001726 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001727 switch (PredR) {
1728 default:
1729 llvm_unreachable("Unknown integer condition code!");
1730 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001731 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001732 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001733 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001734 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1735 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001736 }
1737 break;
1738 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001739 switch (PredR) {
1740 default:
1741 llvm_unreachable("Unknown integer condition code!");
1742 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001743 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001744 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001745 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001746 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001747 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001748 }
1749 break;
1750 }
Craig Topperf40110f2014-04-25 05:29:35 +00001751 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001752}
1753
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001754// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1755// here. We should standardize that construct where it is needed or choose some
1756// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001758 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001759 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1760
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001761 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001762 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001763
Craig Toppera4205622017-06-09 03:21:29 +00001764 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001765 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001766
Craig Topper9d4171a2012-12-20 07:09:41 +00001767 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001768 // purpose is to compute bits we don't care about.
1769 if (SimplifyDemandedInstructionBits(I))
1770 return &I;
1771
Sanjay Patele0c26e02017-04-23 22:00:02 +00001772 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001773 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001774 return Xor;
1775
1776 // (A&B)|(A&C) -> A&(B|C) etc
1777 if (Value *V = SimplifyUsingDistributiveLaws(I))
1778 return replaceInstUsesWith(I, V);
1779
Craig Topper95e41422017-07-06 16:24:23 +00001780 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001781 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001782
Craig Topper86173602017-04-04 20:26:25 +00001783 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001784 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1785 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001786
Chad Rosiere5819e22016-05-26 14:58:51 +00001787 // Given an OR instruction, check to see if this is a bswap.
1788 if (Instruction *BSwap = MatchBSwap(I))
1789 return BSwap;
1790
Craig Topperafa07c52017-04-09 06:12:41 +00001791 {
1792 Value *A;
1793 const APInt *C;
1794 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1795 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1796 MaskedValueIsZero(Op1, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001797 Value *NOr = Builder.CreateOr(A, Op1);
Craig Topperafa07c52017-04-09 06:12:41 +00001798 NOr->takeName(Op0);
1799 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001800 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001801 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001802
Craig Topperafa07c52017-04-09 06:12:41 +00001803 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1804 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1805 MaskedValueIsZero(Op0, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001806 Value *NOr = Builder.CreateOr(A, Op0);
Craig Topperafa07c52017-04-09 06:12:41 +00001807 NOr->takeName(Op0);
1808 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001809 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001810 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811 }
1812
Craig Topperafa07c52017-04-09 06:12:41 +00001813 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001814
1815 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00001816 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperafa07c52017-04-09 06:12:41 +00001819 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topperf7200992017-08-14 00:04:21 +00001822 Value *V1 = nullptr, *V2 = nullptr;
Craig Topper73ba1c82017-06-07 07:40:37 +00001823 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00001824 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001825 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001826 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001827 ((V1 == B &&
1828 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
1829 (V2 == B &&
1830 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00001832 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001833 // Or commutes, try both ways.
1834 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001835 ((V1 == A &&
1836 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
1837 (V2 == A &&
1838 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001839 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00001840 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001841
Chris Lattner95188692010-01-11 06:55:24 +00001842 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001843 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00001844 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00001845 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001846 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00001847 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001848 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001849 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00001850 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00001851 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001852 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001853 }
Craig Topperf7200992017-08-14 00:04:21 +00001854
1855 if (C1->getValue() == ~C2->getValue()) {
1856 Value *X;
1857
1858 // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
1859 if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
1860 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
1861 // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
1862 if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
1863 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
1864
1865 // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
1866 if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
1867 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
1868 // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
1869 if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
1870 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
1871 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001872 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001873
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001874 // Don't try to form a select if it's unlikely that we'll get rid of at
1875 // least one of the operands. A select is generally more expensive than the
1876 // 'or' that it is replacing.
1877 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1878 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Craig Topperbb4069e2017-07-07 23:16:26 +00001879 if (Value *V = matchSelectFromAndOr(A, C, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001880 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001881 if (Value *V = matchSelectFromAndOr(A, C, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001882 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001883 if (Value *V = matchSelectFromAndOr(C, A, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001884 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001885 if (Value *V = matchSelectFromAndOr(C, A, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001886 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001887 if (Value *V = matchSelectFromAndOr(B, D, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001888 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001889 if (Value *V = matchSelectFromAndOr(B, D, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001890 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001891 if (Value *V = matchSelectFromAndOr(D, B, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001892 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001893 if (Value *V = matchSelectFromAndOr(D, B, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001894 return replaceInstUsesWith(I, V);
1895 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001896 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001897
David Majnemer42af3602014-07-30 21:26:37 +00001898 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
1899 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1900 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001901 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00001902
1903 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
1904 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1905 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001906 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00001907
David Majnemerf1eda232014-08-14 06:41:38 +00001908 // ((B | C) & A) | B -> B | (A & C)
1909 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00001910 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00001911
Craig Topperbb4069e2017-07-07 23:16:26 +00001912 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001913 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001914
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001915 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00001916 bool SwappedForXor = false;
1917 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001918 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00001919 SwappedForXor = true;
1920 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001921
1922 // A | ( A ^ B) -> A | B
1923 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00001924 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001925 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1926 if (Op0 == A || Op0 == B)
1927 return BinaryOperator::CreateOr(A, B);
1928
Chad Rosier7813dce2012-04-26 23:29:14 +00001929 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1930 match(Op0, m_And(m_Specific(B), m_Specific(A))))
1931 return BinaryOperator::CreateOr(A, B);
1932
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001933 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001934 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001935 return BinaryOperator::CreateOr(Not, Op0);
1936 }
1937 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001938 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001939 return BinaryOperator::CreateOr(Not, Op0);
1940 }
1941 }
1942
1943 // A | ~(A | B) -> A | ~B
1944 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001945 if (match(Op1, m_Not(m_Value(A))))
1946 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001947 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1948 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1949 B->getOpcode() == Instruction::Xor)) {
1950 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1951 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00001952 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001953 return BinaryOperator::CreateOr(Not, Op0);
1954 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001955
Eli Friedmane06535b2012-03-16 00:52:42 +00001956 if (SwappedForXor)
1957 std::swap(Op0, Op1);
1958
David Majnemer3d6f80b2014-11-28 19:58:29 +00001959 {
1960 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1961 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1962 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001963 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001964 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001965
David Majnemer3d6f80b2014-11-28 19:58:29 +00001966 // TODO: Make this recursive; it's a little tricky because an arbitrary
1967 // number of 'or' instructions might have to be created.
1968 Value *X, *Y;
1969 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1970 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001971 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001972 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00001973 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001974 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001975 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00001976 }
1977 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1978 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001979 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001980 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00001981 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001982 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001983 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00001984 }
1985 }
1986
Chris Lattner4e8137d2010-02-11 06:26:33 +00001987 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1988 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001989 if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00001990 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001991
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001992 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
1993 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00001994
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00001995 // 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 +00001996 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001997 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00001998 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00001999 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002000 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002001 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2002
Owen Andersonc237a842010-09-13 17:59:27 +00002003 // Note: If we've gotten to the point of visiting the outer OR, then the
2004 // inner one couldn't be simplified. If it was a constant, then it won't
2005 // be simplified by a later pass either, so we try swapping the inner/outer
2006 // ORs in the hopes that we'll be able to simplify it this way.
2007 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002008 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002009 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2010 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002011 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002012 Inner->takeName(Op0);
2013 return BinaryOperator::CreateOr(Inner, C1);
2014 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002015
Bill Wendling23242092013-02-16 23:41:36 +00002016 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2017 // Since this OR statement hasn't been optimized further yet, we hope
2018 // that this transformation will allow the new ORs to be optimized.
2019 {
Craig Topperf40110f2014-04-25 05:29:35 +00002020 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002021 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2022 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2023 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002024 Value *orTrue = Builder.CreateOr(A, C);
2025 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002026 return SelectInst::Create(X, orTrue, orFalse);
2027 }
2028 }
2029
Craig Topperf40110f2014-04-25 05:29:35 +00002030 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002031}
2032
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002033/// A ^ B can be specified using other logic ops in a variety of patterns. We
2034/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002035static Instruction *foldXorToXor(BinaryOperator &I,
2036 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002037 assert(I.getOpcode() == Instruction::Xor);
2038 Value *Op0 = I.getOperand(0);
2039 Value *Op1 = I.getOperand(1);
2040 Value *A, *B;
2041
2042 // There are 4 commuted variants for each of the basic patterns.
2043
2044 // (A & B) ^ (A | B) -> A ^ B
2045 // (A & B) ^ (B | A) -> A ^ B
2046 // (A | B) ^ (A & B) -> A ^ B
2047 // (A | B) ^ (B & A) -> A ^ B
2048 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2049 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2050 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2051 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2052 I.setOperand(0, A);
2053 I.setOperand(1, B);
2054 return &I;
2055 }
2056
2057 // (A | ~B) ^ (~A | B) -> A ^ B
2058 // (~B | A) ^ (~A | B) -> A ^ B
2059 // (~A | B) ^ (A | ~B) -> A ^ B
2060 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002061 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2062 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2063 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2064 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002065 I.setOperand(0, A);
2066 I.setOperand(1, B);
2067 return &I;
2068 }
2069
2070 // (A & ~B) ^ (~A & B) -> A ^ B
2071 // (~B & A) ^ (~A & B) -> A ^ B
2072 // (~A & B) ^ (A & ~B) -> A ^ B
2073 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002074 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2075 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2076 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2077 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002078 I.setOperand(0, A);
2079 I.setOperand(1, B);
2080 return &I;
2081 }
2082
Craig Topperf60ab472017-07-02 01:15:51 +00002083 // For the remaining cases we need to get rid of one of the operands.
2084 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2085 return nullptr;
2086
2087 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2088 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2089 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2090 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2091 // Complexity sorting ensures the not will be on the right side.
2092 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2093 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2094 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2095 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2096 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2097
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002098 return nullptr;
2099}
2100
Sanjay Patel5e456b92017-05-18 20:53:16 +00002101Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2102 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2103 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2104 LHS->getOperand(1) == RHS->getOperand(0))
2105 LHS->swapOperands();
2106 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2107 LHS->getOperand(1) == RHS->getOperand(1)) {
2108 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2109 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2110 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2111 bool isSigned = LHS->isSigned() || RHS->isSigned();
2112 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2113 }
2114 }
2115
Sanjay Pateladca8252017-06-20 12:40:55 +00002116 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2117 // into those logic ops. That is, try to turn this into an and-of-icmps
2118 // because we have many folds for that pattern.
2119 //
2120 // This is based on a truth table definition of xor:
2121 // X ^ Y --> (X | Y) & !(X & Y)
2122 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2123 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2124 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2125 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2126 // TODO: Independently handle cases where the 'and' side is a constant.
2127 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2128 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2129 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002130 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002131 }
2132 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002133 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002134 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002135 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002136 }
2137 }
2138 }
2139
Sanjay Patel5e456b92017-05-18 20:53:16 +00002140 return nullptr;
2141}
2142
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002143// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2144// here. We should standardize that construct where it is needed or choose some
2145// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002147 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2149
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002150 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002151 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002152
Craig Toppera4205622017-06-09 03:21:29 +00002153 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002154 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002155
Craig Topperbb4069e2017-07-07 23:16:26 +00002156 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002157 return NewXor;
2158
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002159 // (A&B)^(A&C) -> A&(B^C) etc
2160 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002161 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002162
Craig Topper9d4171a2012-12-20 07:09:41 +00002163 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002164 // purpose is to compute bits we don't care about.
2165 if (SimplifyDemandedInstructionBits(I))
2166 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002167
Craig Topper95e41422017-07-06 16:24:23 +00002168 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002169 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002170
Sanjay Patel6381db12017-05-02 15:31:40 +00002171 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2172 Value *X, *Y;
2173
2174 // We must eliminate the and/or (one-use) for these transforms to not increase
2175 // the instruction count.
2176 // ~(~X & Y) --> (X | ~Y)
2177 // ~(Y & ~X) --> (X | ~Y)
2178 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002179 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002180 return BinaryOperator::CreateOr(X, NotY);
2181 }
2182 // ~(~X | Y) --> (X & ~Y)
2183 // ~(Y | ~X) --> (X & ~Y)
2184 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002185 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002186 return BinaryOperator::CreateAnd(X, NotY);
2187 }
2188
Sanjay Patel3b863f82017-04-22 18:05:35 +00002189 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002190 BinaryOperator *NotVal;
2191 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2192 if (NotVal->getOpcode() == Instruction::And ||
2193 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002194 // Apply DeMorgan's Law when inverts are free:
2195 // ~(X & Y) --> (~X | ~Y)
2196 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002197 if (IsFreeToInvert(NotVal->getOperand(0),
2198 NotVal->getOperand(0)->hasOneUse()) &&
2199 IsFreeToInvert(NotVal->getOperand(1),
2200 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002201 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2202 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002203 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002204 return BinaryOperator::CreateOr(NotX, NotY);
2205 return BinaryOperator::CreateAnd(NotX, NotY);
2206 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002207 }
2208
2209 // ~(~X >>s Y) --> (X >>s Y)
2210 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2211 return BinaryOperator::CreateAShr(X, Y);
2212
2213 // If we are inverting a right-shifted constant, we may be able to eliminate
2214 // the 'not' by inverting the constant and using the opposite shift type.
2215 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2216 // but we must check that in case that transform has not fired yet.
2217 const APInt *C;
2218 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2219 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2220 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2221 return BinaryOperator::CreateLShr(NotC, Y);
2222 }
2223
2224 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2225 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2226 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2227 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002228 }
2229 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002230
Craig Topper798a19a2017-06-29 00:07:08 +00002231 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002232 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002233 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002234 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2235 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002236 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002237
Craig Topperb5bf0162017-08-06 06:28:41 +00002238 {
2239 const APInt *RHSC;
2240 if (match(Op1, m_APInt(RHSC))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002241 Value *X;
Craig Topperb5bf0162017-08-06 06:28:41 +00002242 const APInt *C;
Craig Topper9a6110b2017-08-10 20:35:34 +00002243 if (match(Op0, m_Sub(m_APInt(C), m_Value(X)))) {
Craig Topperb5bf0162017-08-06 06:28:41 +00002244 // ~(c-X) == X-c-1 == X+(-c-1)
2245 if (RHSC->isAllOnesValue()) {
2246 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
Craig Topper9a6110b2017-08-10 20:35:34 +00002247 return BinaryOperator::CreateAdd(X, NewC);
Craig Topperb5bf0162017-08-06 06:28:41 +00002248 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002249 if (RHSC->isSignMask()) {
2250 // (C - X) ^ signmask -> (C + signmask - X)
2251 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
Craig Topper9a6110b2017-08-10 20:35:34 +00002252 return BinaryOperator::CreateSub(NewC, X);
Craig Topper9cbdbef2017-08-06 22:17:21 +00002253 }
Craig Topper9a6110b2017-08-10 20:35:34 +00002254 } else if (match(Op0, m_Add(m_Value(X), m_APInt(C)))) {
Craig Topperb5bf0162017-08-06 06:28:41 +00002255 // ~(X-c) --> (-c-1)-X
2256 if (RHSC->isAllOnesValue()) {
2257 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
Craig Topper9a6110b2017-08-10 20:35:34 +00002258 return BinaryOperator::CreateSub(NewC, X);
Craig Topperb5bf0162017-08-06 06:28:41 +00002259 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002260 if (RHSC->isSignMask()) {
2261 // (X + C) ^ signmask -> (X + C + signmask)
2262 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
Craig Topper9a6110b2017-08-10 20:35:34 +00002263 return BinaryOperator::CreateAdd(X, NewC);
Craig Topper9cbdbef2017-08-06 22:17:21 +00002264 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002265 }
Craig Topper9a6110b2017-08-10 20:35:34 +00002266
2267 // (X|C1)^C2 -> X^(C1^C2) iff X&~C1 == 0
2268 if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
2269 MaskedValueIsZero(X, *C, 0, &I)) {
2270 Constant *NewC = ConstantInt::get(I.getType(), *C ^ *RHSC);
2271 Worklist.Add(cast<Instruction>(Op0));
2272 I.setOperand(0, X);
2273 I.setOperand(1, NewC);
2274 return &I;
2275 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002276 }
2277 }
2278
Craig Topper9d1821b2017-04-09 06:12:31 +00002279 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002280 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002281 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002282 if (Op0I->getOpcode() == Instruction::LShr) {
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002283 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2284 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002285 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002286 ConstantInt *C1;
2287 if (Op0I->hasOneUse() &&
2288 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2289 E1->getOpcode() == Instruction::Xor &&
2290 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2291 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002292 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002293 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2294 FoldConst ^= C3->getValue();
2295 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002296 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002297 Opnd0->takeName(Op0I);
2298 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2299 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2300
2301 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2302 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002303 }
2304 }
2305 }
Craig Topper86173602017-04-04 20:26:25 +00002306 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002307
Craig Topper86173602017-04-04 20:26:25 +00002308 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002309 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2310 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002311
Craig Topper76394602017-04-10 06:53:23 +00002312 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002313 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002314 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002315 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002316 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002317 std::swap(A, B);
2318 }
2319 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002320 I.swapOperands(); // Simplified below.
2321 std::swap(Op0, Op1);
2322 }
Craig Topper76394602017-04-10 06:53:23 +00002323 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002324 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002325 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002326 std::swap(A, B);
2327 }
2328 if (B == Op0) { // A^(B&A) -> (B&A)^A
2329 I.swapOperands(); // Simplified below.
2330 std::swap(Op0, Op1);
2331 }
2332 }
2333 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002334
Craig Topper76394602017-04-10 06:53:23 +00002335 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002336 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002337 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002338 if (A == Op1) // (B|A)^B == (A|B)^B
2339 std::swap(A, B);
2340 if (B == Op1) // (A|B)^B == A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00002341 return BinaryOperator::CreateAnd(A, Builder.CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002342 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002343 if (A == Op1) // (A&B)^A -> (B&A)^A
2344 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002345 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002346 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002347 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Craig Topperbb4069e2017-07-07 23:16:26 +00002348 return BinaryOperator::CreateAnd(Builder.CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002349 }
2350 }
2351 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002352
Craig Topper76394602017-04-10 06:53:23 +00002353 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002354 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002355 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002356 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2357 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002358 if (D == A)
2359 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002360 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002361 if (D == B)
2362 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002363 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002364 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002365 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002366 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2367 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002368 if (D == A)
2369 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002370 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002371 if (D == B)
2372 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002373 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002374 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002375 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002376 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002377 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002378 return BinaryOperator::CreateOr(A, B);
2379 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002380 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002381 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002382 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002383 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002384
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002385 // (A & ~B) ^ ~A -> ~(A & B)
2386 // (~B & A) ^ ~A -> ~(A & B)
2387 Value *A, *B;
2388 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002389 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002390 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002391
Sanjay Patel5e456b92017-05-18 20:53:16 +00002392 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2393 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2394 if (Value *V = foldXorOfICmps(LHS, RHS))
2395 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002396
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002397 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2398 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002399
Craig Topperf40110f2014-04-25 05:29:35 +00002400 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002401}