blob: 0aea1edb0d0b6aa9c4ff5330c8f8873c51804e5e [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
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
Sanjay Patel77bf6222017-04-03 16:53:12 +0000295/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
296/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
297/// RHS satisfy.
298static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
299 Value *&D, Value *&E, ICmpInst *LHS,
300 ICmpInst *RHS,
301 ICmpInst::Predicate &PredL,
302 ICmpInst::Predicate &PredR) {
303 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
304 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000305 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000306 if (LHS->getOperand(0)->getType()->isVectorTy())
307 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000308
309 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000310 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000311 // and L11 & L12 == L21 & L22. The same goes for RHS.
312 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000313 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000314 // above.
315 Value *L1 = LHS->getOperand(0);
316 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000317 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000318 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000319 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000320 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000321 } else {
322 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000323 if (!L1->getType()->isIntegerTy()) {
324 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000325 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000326 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
327 // Any icmp can be viewed as being trivially masked; if it allows us to
328 // remove one, it's worth it.
329 L11 = L1;
330 L12 = Constant::getAllOnesValue(L1->getType());
331 }
332
333 if (!L2->getType()->isIntegerTy()) {
334 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000335 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000336 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
337 L21 = L2;
338 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000339 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000340 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000341
342 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000343 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000344 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345
346 Value *R1 = RHS->getOperand(0);
347 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348 Value *R11, *R12;
349 bool Ok = false;
350 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000351 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000352 A = R11;
353 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000354 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000355 A = R12;
356 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000357 } else {
358 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000359 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000360 E = R2;
361 R1 = nullptr;
362 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000363 } else if (R1->getType()->isIntegerTy()) {
364 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
365 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000366 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000367 R11 = R1;
368 R12 = Constant::getAllOnesValue(R1->getType());
369 }
370
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000371 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000372 A = R11;
373 D = R12;
374 E = R2;
375 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000376 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000377 A = R12;
378 D = R11;
379 E = R2;
380 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000381 }
382 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000383
384 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000385 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000386 return 0;
387
Chad Rosier58919cc2016-05-09 21:37:43 +0000388 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000389 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000390 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
391 R11 = R2;
392 R12 = Constant::getAllOnesValue(R2->getType());
393 }
394
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000395 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000396 A = R11;
397 D = R12;
398 E = R1;
399 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000400 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000401 A = R12;
402 D = R11;
403 E = R1;
404 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000405 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000406 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000407 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000408 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000409 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000410 return 0;
411
412 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000413 B = L12;
414 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000415 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000416 B = L11;
417 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000418 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000419 B = L22;
420 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000421 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000422 B = L21;
423 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 }
425
Sanjay Patel77bf6222017-04-03 16:53:12 +0000426 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
427 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000428 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429}
Sanjay Patel18549272015-09-08 18:24:36 +0000430
431/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
432/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000433static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000434 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000435 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000436 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
437 unsigned Mask =
438 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
439 if (Mask == 0)
440 return nullptr;
441
442 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
443 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000444
Tim Northoverc0756c42013-09-04 11:57:13 +0000445 // In full generality:
446 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
447 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
448 //
449 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
450 // equivalent to (icmp (A & X) !Op Y).
451 //
452 // Therefore, we can pretend for the rest of this function that we're dealing
453 // with the conjunction, provided we flip the sense of any comparisons (both
454 // input and output).
455
456 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000457 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000458 if (!IsAnd) {
459 // Convert the masking analysis into its equivalent with negated
460 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000461 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000462 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000463
Sanjay Patel77bf6222017-04-03 16:53:12 +0000464 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000465 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000467 Value *NewOr = Builder.CreateOr(B, D);
468 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000469 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000470 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000471 // with B and D, having a single bit set.
472 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000473 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000474 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000475 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000476 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000477 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000478 Value *NewOr = Builder.CreateOr(B, D);
479 Value *NewAnd = Builder.CreateAnd(A, NewOr);
480 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000481 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000482 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000483 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000484 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000485 Value *NewAnd1 = Builder.CreateAnd(B, D);
486 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
487 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000488 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000489
490 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000491 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000492 // easy cases for now" decision.
493 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000494 if (!BCst)
495 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000496 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000497 if (!DCst)
498 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000499
Sanjay Patel77bf6222017-04-03 16:53:12 +0000500 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000501 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
502 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
503 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
504 // Only valid if one of the masks is a superset of the other (check "B&D" is
505 // the same as either B or D).
506 APInt NewMask = BCst->getValue() & DCst->getValue();
507
508 if (NewMask == BCst->getValue())
509 return LHS;
510 else if (NewMask == DCst->getValue())
511 return RHS;
512 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000513
514 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000515 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
516 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
517 // Only valid if one of the masks is a superset of the other (check "B|D" is
518 // the same as either B or D).
519 APInt NewMask = BCst->getValue() | DCst->getValue();
520
521 if (NewMask == BCst->getValue())
522 return LHS;
523 else if (NewMask == DCst->getValue())
524 return RHS;
525 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000526
527 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000528 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000529 // We already know that B & C == C && D & E == E.
530 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
531 // C and E, which are shared by both the mask B and the mask D, don't
532 // contradict, then we can transform to
533 // -> (icmp eq (A & (B|D)), (C|E))
534 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000535 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000536 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000537 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000538 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000539 if (!CCst)
540 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000541 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000542 if (!ECst)
543 return nullptr;
544 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000545 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000546 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000547 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000548
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000549 // If there is a conflict, we should actually return a false for the
550 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000551 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000552 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000553 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000554
Craig Topperbb4069e2017-07-07 23:16:26 +0000555 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000556 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000557 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
558 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000560
Craig Topperf40110f2014-04-25 05:29:35 +0000561 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000562}
563
Erik Ecksteind1817522014-12-03 10:39:15 +0000564/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
565/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
566/// If \p Inverted is true then the check is for the inverted range, e.g.
567/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
568Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
569 bool Inverted) {
570 // Check the lower range comparison, e.g. x >= 0
571 // InstCombine already ensured that if there is a constant it's on the RHS.
572 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
573 if (!RangeStart)
574 return nullptr;
575
576 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
577 Cmp0->getPredicate());
578
579 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
580 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
581 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
582 return nullptr;
583
584 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
585 Cmp1->getPredicate());
586
587 Value *Input = Cmp0->getOperand(0);
588 Value *RangeEnd;
589 if (Cmp1->getOperand(0) == Input) {
590 // For the upper range compare we have: icmp x, n
591 RangeEnd = Cmp1->getOperand(1);
592 } else if (Cmp1->getOperand(1) == Input) {
593 // For the upper range compare we have: icmp n, x
594 RangeEnd = Cmp1->getOperand(0);
595 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
596 } else {
597 return nullptr;
598 }
599
600 // Check the upper range comparison, e.g. x < n
601 ICmpInst::Predicate NewPred;
602 switch (Pred1) {
603 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
604 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
605 default: return nullptr;
606 }
607
608 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000609 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
610 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000611 return nullptr;
612
613 if (Inverted)
614 NewPred = ICmpInst::getInversePredicate(NewPred);
615
Craig Topperbb4069e2017-07-07 23:16:26 +0000616 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000617}
618
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000619static Value *
620foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
621 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000622 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000623 Value *X = LHS->getOperand(0);
624 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000625 return nullptr;
626
Sanjay Patelef9f5862017-04-15 17:55:06 +0000627 const APInt *C1, *C2;
628 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
629 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000630 return nullptr;
631
632 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
633 ICmpInst::Predicate Pred = LHS->getPredicate();
634 if (Pred != RHS->getPredicate())
635 return nullptr;
636 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
637 return nullptr;
638 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
639 return nullptr;
640
641 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000642 if (C1->ugt(*C2))
643 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000644
Sanjay Patelef9f5862017-04-15 17:55:06 +0000645 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000646 if (Xor.isPowerOf2()) {
647 // If LHSC and RHSC differ by only one bit, then set that bit in X and
648 // compare against the larger constant:
649 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
650 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
651 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
652 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000653 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
654 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000655 }
656
657 // Special case: get the ordering right when the values wrap around zero.
658 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000659 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000660 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000661
Sanjay Patelef9f5862017-04-15 17:55:06 +0000662 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000663 // (X == 13 || X == 14) --> X - 13 <=u 1
664 // (X != 13 && X != 14) --> X - 13 >u 1
665 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000666 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000667 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000668 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000669 }
670
671 return nullptr;
672}
673
Craig Topperda6ea0d2017-06-16 05:10:37 +0000674// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
675// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
676Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
677 bool JoinedByAnd,
678 Instruction &CxtI) {
679 ICmpInst::Predicate Pred = LHS->getPredicate();
680 if (Pred != RHS->getPredicate())
681 return nullptr;
682 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
683 return nullptr;
684 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
685 return nullptr;
686
687 // TODO support vector splats
688 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
689 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
690 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
691 return nullptr;
692
693 Value *A, *B, *C, *D;
694 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
695 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
696 if (A == D || B == D)
697 std::swap(C, D);
698 if (B == C)
699 std::swap(A, B);
700
701 if (A == C &&
702 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
703 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000704 Value *Mask = Builder.CreateOr(B, D);
705 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000706 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000707 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000708 }
709 }
710
711 return nullptr;
712}
713
Sanjay Patel18549272015-09-08 18:24:36 +0000714/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000715Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
716 Instruction &CxtI) {
717 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
718 // if K1 and K2 are a one-bit mask.
719 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
720 return V;
721
Sanjay Patel519a87a2017-04-05 17:38:34 +0000722 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000723
724 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000725 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000726 if (LHS->getOperand(0) == RHS->getOperand(1) &&
727 LHS->getOperand(1) == RHS->getOperand(0))
728 LHS->swapOperands();
729 if (LHS->getOperand(0) == RHS->getOperand(0) &&
730 LHS->getOperand(1) == RHS->getOperand(1)) {
731 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
732 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
733 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000734 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000735 }
736 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000737
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000738 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000739 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000740 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000741
Erik Ecksteind1817522014-12-03 10:39:15 +0000742 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
743 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
744 return V;
745
746 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
747 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
748 return V;
749
Sanjay Patelef9f5862017-04-15 17:55:06 +0000750 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
751 return V;
752
Chris Lattner0a8191e2010-01-05 07:50:36 +0000753 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000754 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000755 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
756 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
757 if (!LHSC || !RHSC)
758 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000759
Sanjay Patel519a87a2017-04-05 17:38:34 +0000760 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000761 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000762 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000763 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000764 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
765 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000766 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
767 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000768 }
769 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000770
Benjamin Kramer101720f2011-04-28 20:09:57 +0000771 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000772 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000773 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000774 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
775 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000776 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000777 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000778
779 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000780 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000781 if (match(RHS0, m_Trunc(m_Value(V))) &&
782 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000783 SmallC = RHSC;
784 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000785 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
786 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000787 SmallC = LHSC;
788 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000789 }
790
Sanjay Patel519a87a2017-04-05 17:38:34 +0000791 if (SmallC && BigC) {
792 unsigned BigBitSize = BigC->getType()->getBitWidth();
793 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000794
795 // Check that the low bits are zero.
796 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000797 if ((Low & AndC->getValue()).isNullValue() &&
798 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000799 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +0000800 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
801 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +0000802 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000803 }
804 }
805 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000806
Chris Lattner0a8191e2010-01-05 07:50:36 +0000807 // From here on, we only handle:
808 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000809 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000810 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000811
Sanjay Patel519a87a2017-04-05 17:38:34 +0000812 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
813 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
814 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
815 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
816 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000817 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000818
Chris Lattner0a8191e2010-01-05 07:50:36 +0000819 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000820 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000821 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000822
Chris Lattner0a8191e2010-01-05 07:50:36 +0000823 // Ensure that the larger constant is on the RHS.
824 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000825 if (CmpInst::isSigned(PredL) ||
826 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000827 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000828 else
829 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000830
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 if (ShouldSwap) {
832 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000833 std::swap(LHSC, RHSC);
834 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000835 }
836
Dan Gohman4a618822010-02-10 16:03:48 +0000837 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000838 // comparing a value against two constants and and'ing the result
839 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000840 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
841 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000842 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000843 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000844
Sanjay Patel519a87a2017-04-05 17:38:34 +0000845 switch (PredL) {
846 default:
847 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000848 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000849 switch (PredR) {
850 default:
851 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000852 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000853 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000854 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000855 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000856 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000857 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000858 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000859 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000860 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000861 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000862 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000863 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000864 // Potential folds for this case should already be handled.
865 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000866 }
867 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000868 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000869 switch (PredR) {
870 default:
871 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000872 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000873 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000874 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000875 break; // (X u> 13 & X != 15) -> no change
876 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000877 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
878 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000879 }
880 break;
881 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000882 switch (PredR) {
883 default:
884 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000885 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000886 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000887 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000888 break; // (X s> 13 & X != 15) -> no change
889 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000890 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000891 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000892 }
893 break;
894 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000895
Craig Topperf40110f2014-04-25 05:29:35 +0000896 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897}
898
Sanjay Patel18549272015-09-08 18:24:36 +0000899/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
900/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000901Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000902 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
903 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
904 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
905
906 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
907 // Swap RHS operands to match LHS.
908 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
909 std::swap(Op1LHS, Op1RHS);
910 }
911
912 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
913 // Suppose the relation between x and y is R, where R is one of
914 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
915 // testing the desired relations.
916 //
917 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
918 // bool(R & CC0) && bool(R & CC1)
919 // = bool((R & CC0) & (R & CC1))
920 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
921 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
922 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
923 Builder);
924
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
926 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +0000927 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000928 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +0000929
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
931 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
932 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
933 // If either of the constants are nans, then the whole thing returns
934 // false.
935 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +0000936 return Builder.getFalse();
937 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000938 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000939
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 // Handle vector zeros. This occurs because the canonical form of
941 // "fcmp ord x,x" is "fcmp ord x, 0".
942 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
943 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +0000944 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +0000945 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000946 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000947
Craig Topperf40110f2014-04-25 05:29:35 +0000948 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949}
950
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000951/// Match De Morgan's Laws:
952/// (~A & ~B) == (~(A | B))
953/// (~A | ~B) == (~(A & B))
954static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +0000955 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000956 auto Opcode = I.getOpcode();
957 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
958 "Trying to match De Morgan's Laws with something other than and/or");
959
Sanjay Patel7caaa792017-05-09 20:05:05 +0000960 // Flip the logic operation.
961 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
962
963 Value *A, *B;
964 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
965 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
966 !IsFreeToInvert(A, A->hasOneUse()) &&
967 !IsFreeToInvert(B, B->hasOneUse())) {
968 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
969 return BinaryOperator::CreateNot(AndOr);
970 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000971
972 return nullptr;
973}
974
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000975bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
976 Value *CastSrc = CI->getOperand(0);
977
978 // Noop casts and casts of constants should be eliminated trivially.
979 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
980 return false;
981
982 // If this cast is paired with another cast that can be eliminated, we prefer
983 // to have it eliminated.
984 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
985 if (isEliminableCastPair(PrecedingCI, CI))
986 return false;
987
988 // If this is a vector sext from a compare, then we don't want to break the
989 // idiom where each element of the extended vector is either zero or all ones.
990 if (CI->getOpcode() == Instruction::SExt &&
991 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
992 return false;
993
994 return true;
995}
996
Sanjay Patel60312bc42016-09-12 00:16:23 +0000997/// Fold {and,or,xor} (cast X), C.
998static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +0000999 InstCombiner::BuilderTy &Builder) {
Craig Topper5706c012017-08-09 06:17:48 +00001000 Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1001 if (!C)
Sanjay Patel60312bc42016-09-12 00:16:23 +00001002 return nullptr;
1003
1004 auto LogicOpc = Logic.getOpcode();
1005 Type *DestTy = Logic.getType();
1006 Type *SrcTy = Cast->getSrcTy();
1007
Craig Topperae9b87d2017-08-02 20:25:56 +00001008 // Move the logic operation ahead of a zext or sext if the constant is
1009 // unchanged in the smaller source type. Performing the logic in a smaller
1010 // type may provide more information to later folds, and the smaller logic
1011 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001012 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001013 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1014 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1015 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1016 if (ZextTruncC == C) {
1017 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001018 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001019 return new ZExtInst(NewOp, DestTy);
1020 }
1021 }
1022
Craig Topperae9b87d2017-08-02 20:25:56 +00001023 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1024 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1025 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1026 if (SextTruncC == C) {
1027 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1028 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1029 return new SExtInst(NewOp, DestTy);
1030 }
1031 }
1032
Sanjay Patel60312bc42016-09-12 00:16:23 +00001033 return nullptr;
1034}
1035
1036/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001037Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001038 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001039 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001040
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001042 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001043 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001044 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001045
Sanjay Patel9bba7502016-03-03 19:19:04 +00001046 // This must be a cast from an integer or integer vector source type to allow
1047 // transformation of the logic operation to the source type.
1048 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001049 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001050 if (!SrcTy->isIntOrIntVectorTy())
1051 return nullptr;
1052
Sanjay Patel60312bc42016-09-12 00:16:23 +00001053 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1054 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001055
Sanjay Patel9bba7502016-03-03 19:19:04 +00001056 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1057 if (!Cast1)
1058 return nullptr;
1059
1060 // Both operands of the logic operation are casts. The casts must be of the
1061 // same type for reduction.
1062 auto CastOpcode = Cast0->getOpcode();
1063 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001064 return nullptr;
1065
1066 Value *Cast0Src = Cast0->getOperand(0);
1067 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001068
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001069 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001070 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001071 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001072 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001073 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001074 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001075
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001076 // For now, only 'and'/'or' have optimizations after this.
1077 if (LogicOpc == Instruction::Xor)
1078 return nullptr;
1079
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001080 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001081 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001082 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1083 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1084 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001085 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001086 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001087 if (Res)
1088 return CastInst::Create(CastOpcode, Res, DestTy);
1089 return nullptr;
1090 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001091
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001092 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001093 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001094 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1095 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1096 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001097 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1098 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001099 if (Res)
1100 return CastInst::Create(CastOpcode, Res, DestTy);
1101 return nullptr;
1102 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001103
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001104 return nullptr;
1105}
1106
Sanjay Patele0c26e02017-04-23 22:00:02 +00001107static Instruction *foldAndToXor(BinaryOperator &I,
1108 InstCombiner::BuilderTy &Builder) {
1109 assert(I.getOpcode() == Instruction::And);
1110 Value *Op0 = I.getOperand(0);
1111 Value *Op1 = I.getOperand(1);
1112 Value *A, *B;
1113
1114 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1115 // (A | B) & ~(A & B) --> A ^ B
1116 // (A | B) & ~(B & A) --> A ^ B
1117 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1118 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1119 return BinaryOperator::CreateXor(A, B);
1120
1121 // (A | ~B) & (~A | B) --> ~(A ^ B)
1122 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1123 // (~B | A) & (~A | B) --> ~(A ^ B)
1124 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001125 if (Op0->hasOneUse() || Op1->hasOneUse())
1126 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1127 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1128 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001129
1130 return nullptr;
1131}
1132
1133static Instruction *foldOrToXor(BinaryOperator &I,
1134 InstCombiner::BuilderTy &Builder) {
1135 assert(I.getOpcode() == Instruction::Or);
1136 Value *Op0 = I.getOperand(0);
1137 Value *Op1 = I.getOperand(1);
1138 Value *A, *B;
1139
1140 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1141 // (A & B) | ~(A | B) --> ~(A ^ B)
1142 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001143 if (Op0->hasOneUse() || Op1->hasOneUse())
1144 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1145 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1146 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001147
1148 // (A & ~B) | (~A & B) --> A ^ B
1149 // (A & ~B) | (B & ~A) --> A ^ B
1150 // (~B & A) | (~A & B) --> A ^ B
1151 // (~B & A) | (B & ~A) --> A ^ B
1152 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1153 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1154 return BinaryOperator::CreateXor(A, B);
1155
1156 return nullptr;
1157}
1158
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001159// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1160// here. We should standardize that construct where it is needed or choose some
1161// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001162Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001163 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1165
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001166 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001167 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001168
Craig Toppera4205622017-06-09 03:21:29 +00001169 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001170 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001171
Craig Topper9d4171a2012-12-20 07:09:41 +00001172 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001173 // purpose is to compute bits we don't care about.
1174 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001175 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001176
Sanjay Patele0c26e02017-04-23 22:00:02 +00001177 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001178 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001179 return Xor;
1180
1181 // (A|B)&(A|C) -> A|(B&C) etc
1182 if (Value *V = SimplifyUsingDistributiveLaws(I))
1183 return replaceInstUsesWith(I, V);
1184
Craig Topper95e41422017-07-06 16:24:23 +00001185 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001186 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001187
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001188 const APInt *C;
1189 if (match(Op1, m_APInt(C))) {
1190 Value *X, *Y;
1191 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1192 C->isOneValue()) {
1193 // (1 << X) & 1 --> zext(X == 0)
1194 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001195 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1196 return new ZExtInst(IsZero, I.getType());
1197 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001198
Craig Toppera1693a22017-08-06 23:11:49 +00001199 const APInt *XorC;
1200 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1201 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1202 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1203 Value *And = Builder.CreateAnd(X, Op1);
1204 And->takeName(Op0);
1205 return BinaryOperator::CreateXor(And, NewC);
1206 }
1207
Craig Topper7091a742017-08-07 18:10:39 +00001208 const APInt *OrC;
1209 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1210 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1211 // NOTE: This reduces the number of bits set in the & mask, which
1212 // can expose opportunities for store narrowing for scalars.
1213 // NOTE: SimplifyDemandedBits should have already removed bits from C1
1214 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1215 // above, but this feels safer.
1216 APInt Together = *C & *OrC;
1217 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(),
1218 Together ^ *C));
1219 And->takeName(Op0);
1220 return BinaryOperator::CreateOr(And, ConstantInt::get(I.getType(),
1221 Together));
1222 }
1223
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001224 // If the mask is only needed on one incoming arm, push the 'and' op up.
1225 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1226 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1227 APInt NotAndMask(~(*C));
1228 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1229 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1230 // Not masking anything out for the LHS, move mask to RHS.
1231 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1232 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1233 return BinaryOperator::Create(BinOp, X, NewRHS);
1234 }
1235 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1236 // Not masking anything out for the RHS, move mask to LHS.
1237 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1238 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1239 return BinaryOperator::Create(BinOp, NewLHS, Y);
1240 }
1241 }
Craig Toppera1693a22017-08-06 23:11:49 +00001242
Sanjay Patel3437ee22017-07-15 17:26:01 +00001243 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001244
Chris Lattner0a8191e2010-01-05 07:50:36 +00001245 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1246 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001247
1248 // Optimize a variety of ((val OP C1) & C2) combinations...
1249 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001250 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1251 // of X and OP behaves well when given trunc(C1) and X.
1252 switch (Op0I->getOpcode()) {
1253 default:
1254 break;
1255 case Instruction::Xor:
1256 case Instruction::Or:
1257 case Instruction::Mul:
1258 case Instruction::Add:
1259 case Instruction::Sub:
1260 Value *X;
1261 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001262 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001263 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1264 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1265 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001266 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001267 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001268 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001269 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001270 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001271 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001272 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001273 return new ZExtInst(And, I.getType());
1274 }
1275 }
1276 }
1277
Chris Lattner0a8191e2010-01-05 07:50:36 +00001278 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1279 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1280 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001281 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001282
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001283 // If this is an integer truncation, and if the source is an 'and' with
1284 // immediate, transform it. This frequently occurs for bitfield accesses.
1285 {
Craig Topperf40110f2014-04-25 05:29:35 +00001286 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001287 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1288 // Change: and (trunc (and X, YC) to T), C2
1289 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001290 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001291 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001292 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001293 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1294 C3 = ConstantExpr::getAnd(C3, AndRHS);
1295 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001296 }
1297 }
Craig Topper86173602017-04-04 20:26:25 +00001298 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001299
Craig Topper86173602017-04-04 20:26:25 +00001300 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001301 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1302 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001303
Craig Topperbb4069e2017-07-07 23:16:26 +00001304 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001305 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001306
Chris Lattner0a8191e2010-01-05 07:50:36 +00001307 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001308 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001309 // A&(A^B) => A & ~B
1310 {
1311 Value *tmpOp0 = Op0;
1312 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001313 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001314 if (A == Op1 || B == Op1 ) {
1315 tmpOp1 = Op0;
1316 tmpOp0 = Op1;
1317 // Simplify below
1318 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001320
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001321 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001322 if (B == tmpOp0) {
1323 std::swap(A, B);
1324 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001325 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001326 // A is originally -1 (or a vector of -1 and undefs), then we enter
1327 // an endless loop. By checking that A is non-constant we ensure that
1328 // we will never get to the loop.
1329 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00001330 return BinaryOperator::CreateAnd(A, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001331 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001332 }
1333
David Majnemer42af3602014-07-30 21:26:37 +00001334 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1335 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1336 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001337 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001338 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001339
1340 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1341 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1342 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001343 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001344 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001345
1346 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001347 // (A | B) & (B ^ (~A)) -> (A & B)
1348 // (B | A) & ((~A) ^ B) -> (A & B)
1349 // (B | A) & (B ^ (~A)) -> (A & B)
1350 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1351 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001352 return BinaryOperator::CreateAnd(A, B);
1353
1354 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001355 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001356 // (B ^ (~A)) & (A | B) -> (A & B)
1357 // (B ^ (~A)) & (B | A) -> (A & B)
1358 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001359 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001360 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001361 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001362
David Majnemer5e96f1b2014-08-30 06:18:20 +00001363 {
1364 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1365 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1366 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001367 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001368 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001369
David Majnemer5e96f1b2014-08-30 06:18:20 +00001370 // TODO: Make this recursive; it's a little tricky because an arbitrary
1371 // number of 'and' instructions might have to be created.
1372 Value *X, *Y;
1373 if (LHS && match(Op1, 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(LHS, Cmp, 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(LHS, Cmp, 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 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1382 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001383 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001384 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001385 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001386 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001387 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001388 }
1389 }
1390
Chris Lattner4e8137d2010-02-11 06:26:33 +00001391 // If and'ing two fcmp, try combine them into one.
1392 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1393 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001394 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001395 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001396
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001397 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1398 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001399
Craig Topper760ff6e2017-08-04 16:07:20 +00001400 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1401 Value *A;
1402 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1403 A->getType()->isIntOrIntVectorTy(1))
1404 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1405 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1406 A->getType()->isIntOrIntVectorTy(1))
1407 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001408
Craig Topperf40110f2014-04-25 05:29:35 +00001409 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001410}
1411
Chad Rosiera00df492016-05-25 16:22:14 +00001412/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1413/// insert the new intrinsic and return it.
1414Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1416
1417 // Look through zero extends.
1418 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1419 Op0 = Ext->getOperand(0);
1420
1421 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1422 Op1 = Ext->getOperand(0);
1423
1424 // (A | B) | C and A | (B | C) -> bswap if possible.
1425 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1426 match(Op1, m_Or(m_Value(), m_Value()));
1427
1428 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1429 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1430 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1431
1432 // (A & B) | (C & D) -> bswap if possible.
1433 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1434 match(Op1, m_And(m_Value(), m_Value()));
1435
1436 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1437 return nullptr;
1438
James Molloyf01488e2016-01-15 09:20:19 +00001439 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001440 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001441 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001442 Instruction *LastInst = Insts.pop_back_val();
1443 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001444
James Molloyf01488e2016-01-15 09:20:19 +00001445 for (auto *Inst : Insts)
1446 Worklist.Add(Inst);
1447 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001448}
1449
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001450/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1451static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1452 unsigned NumElts = C1->getType()->getVectorNumElements();
1453 for (unsigned i = 0; i != NumElts; ++i) {
1454 Constant *EltC1 = C1->getAggregateElement(i);
1455 Constant *EltC2 = C2->getAggregateElement(i);
1456 if (!EltC1 || !EltC2)
1457 return false;
1458
1459 // One element must be all ones, and the other must be all zeros.
1460 // FIXME: Allow undef elements.
1461 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1462 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1463 return false;
1464 }
1465 return true;
1466}
1467
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001468/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1469/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1470/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001471static Value *getSelectCondition(Value *A, Value *B,
1472 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001473 // If these are scalars or vectors of i1, A can be used directly.
1474 Type *Ty = A->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001475 if (match(A, m_Not(m_Specific(B))) && Ty->isIntOrIntVectorTy(1))
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001476 return A;
1477
1478 // If A and B are sign-extended, look through the sexts to find the booleans.
1479 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001480 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001481 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001482 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001483 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1484 NotB = peekThroughBitcast(NotB, true);
1485 if (match(NotB, m_SExt(m_Specific(Cond))))
1486 return Cond;
1487 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001488
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001489 // All scalar (and most vector) possibilities should be handled now.
1490 // Try more matches that only apply to non-splat constant vectors.
1491 if (!Ty->isVectorTy())
1492 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001493
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001494 // If both operands are constants, see if the constants are inverse bitmasks.
1495 Constant *AC, *BC;
1496 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1497 areInverseVectorBitmasks(AC, BC))
1498 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1499
1500 // If both operands are xor'd with constants using the same sexted boolean
1501 // operand, see if the constants are inverse bitmasks.
1502 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1503 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001504 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001505 areInverseVectorBitmasks(AC, BC)) {
1506 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1507 return Builder.CreateXor(Cond, AC);
1508 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001509 return nullptr;
1510}
1511
1512/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1513/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001514static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001515 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001516 // The potential condition of the select may be bitcasted. In that case, look
1517 // through its bitcast and the corresponding bitcast of the 'not' condition.
1518 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001519 A = peekThroughBitcast(A, true);
1520 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001521
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001522 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001523 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001524 // The bitcasts will either all exist or all not exist. The builder will
1525 // not create unnecessary casts if the types already match.
1526 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1527 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1528 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1529 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001530 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001531
Craig Topperf40110f2014-04-25 05:29:35 +00001532 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001533}
1534
Sanjay Patel18549272015-09-08 18:24:36 +00001535/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001536Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001537 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001538 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1539 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001540 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1541 return V;
1542
1543 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1544
Sanjay Patel519a87a2017-04-05 17:38:34 +00001545 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1546 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001547
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001548 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1549 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1550 // The original condition actually refers to the following two ranges:
1551 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1552 // We can fold these two ranges if:
1553 // 1) C1 and C2 is unsigned greater than C3.
1554 // 2) The two ranges are separated.
1555 // 3) C1 ^ C2 is one-bit mask.
1556 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1557 // This implies all values in the two ranges differ by exactly one bit.
1558
Sanjay Patel519a87a2017-04-05 17:38:34 +00001559 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1560 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1561 LHSC->getType() == RHSC->getType() &&
1562 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001563
1564 Value *LAdd = LHS->getOperand(0);
1565 Value *RAdd = RHS->getOperand(0);
1566
1567 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001568 ConstantInt *LAddC, *RAddC;
1569 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1570 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1571 LAddC->getValue().ugt(LHSC->getValue()) &&
1572 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001573
Sanjay Patel519a87a2017-04-05 17:38:34 +00001574 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1575 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1576 ConstantInt *MaxAddC = nullptr;
1577 if (LAddC->getValue().ult(RAddC->getValue()))
1578 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001579 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001580 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001581
Sanjay Patel519a87a2017-04-05 17:38:34 +00001582 APInt RRangeLow = -RAddC->getValue();
1583 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1584 APInt LRangeLow = -LAddC->getValue();
1585 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001586 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1587 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1588 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1589 : RRangeLow - LRangeLow;
1590
1591 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001592 RangeDiff.ugt(LHSC->getValue())) {
1593 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001594
Craig Topperbb4069e2017-07-07 23:16:26 +00001595 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1596 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1597 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001598 }
1599 }
1600 }
1601 }
1602
Chris Lattner0a8191e2010-01-05 07:50:36 +00001603 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001604 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001605 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1606 LHS->getOperand(1) == RHS->getOperand(0))
1607 LHS->swapOperands();
1608 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1609 LHS->getOperand(1) == RHS->getOperand(1)) {
1610 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1611 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1612 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001613 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001614 }
1615 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001616
1617 // handle (roughly):
1618 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001619 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001620 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001621
Sanjay Patele4159d22017-04-10 19:38:36 +00001622 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001623 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1624 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1625 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001626 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001627 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001628 B = LHS0;
1629 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1630 A = RHS0;
1631 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001632 A = RHS->getOperand(1);
1633 }
1634 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1635 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001636 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001637 B = RHS0;
1638 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1639 A = LHS0;
1640 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001641 A = LHS->getOperand(1);
1642 }
1643 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00001644 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00001645 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00001646 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00001647 }
1648
Erik Ecksteind1817522014-12-03 10:39:15 +00001649 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1650 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1651 return V;
1652
1653 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1654 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1655 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001656
Sanjay Patelef9f5862017-04-15 17:55:06 +00001657 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1658 return V;
1659
David Majnemerc2a990b2013-07-05 00:31:17 +00001660 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001661 if (!LHSC || !RHSC)
1662 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001663
Sanjay Patel519a87a2017-04-05 17:38:34 +00001664 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001665 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001666 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001667 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1668 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001669 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001670 }
1671
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001672 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001673 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001674 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1675 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001676 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001677 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001678 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001679 }
1680
Chris Lattner0a8191e2010-01-05 07:50:36 +00001681 // From here on, we only handle:
1682 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001683 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001684 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001685
Sanjay Patel519a87a2017-04-05 17:38:34 +00001686 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1687 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1688 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1689 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1690 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001691 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001692
Chris Lattner0a8191e2010-01-05 07:50:36 +00001693 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001694 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001695 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001696
Chris Lattner0a8191e2010-01-05 07:50:36 +00001697 // Ensure that the larger constant is on the RHS.
1698 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001699 if (CmpInst::isSigned(PredL) ||
1700 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001701 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001702 else
1703 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001704
Chris Lattner0a8191e2010-01-05 07:50:36 +00001705 if (ShouldSwap) {
1706 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001707 std::swap(LHSC, RHSC);
1708 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001709 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001710
Dan Gohman4a618822010-02-10 16:03:48 +00001711 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001712 // comparing a value against two constants and or'ing the result
1713 // together. Because of the above check, we know that we only have
1714 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1715 // icmp folding check above), that the two constants are not
1716 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001717 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001718
Sanjay Patel519a87a2017-04-05 17:38:34 +00001719 switch (PredL) {
1720 default:
1721 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001722 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001723 switch (PredR) {
1724 default:
1725 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001726 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001727 // Potential folds for this case should already be handled.
1728 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001729 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1730 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001731 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001732 }
1733 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001734 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001735 switch (PredR) {
1736 default:
1737 llvm_unreachable("Unknown integer condition code!");
1738 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001739 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001740 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001741 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001742 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1743 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001744 }
1745 break;
1746 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001747 switch (PredR) {
1748 default:
1749 llvm_unreachable("Unknown integer condition code!");
1750 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001751 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001752 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001753 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001754 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001755 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001756 }
1757 break;
1758 }
Craig Topperf40110f2014-04-25 05:29:35 +00001759 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001760}
1761
Sanjay Patel18549272015-09-08 18:24:36 +00001762/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1763/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001764Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001765 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1766 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1767 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1768
1769 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1770 // Swap RHS operands to match LHS.
1771 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1772 std::swap(Op1LHS, Op1RHS);
1773 }
1774
1775 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1776 // This is a similar transformation to the one in FoldAndOfFCmps.
1777 //
1778 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1779 // bool(R & CC0) || bool(R & CC1)
1780 // = bool((R & CC0) | (R & CC1))
1781 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1782 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1783 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1784 Builder);
1785
Chris Lattner0a8191e2010-01-05 07:50:36 +00001786 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001787 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001788 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1789 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1790 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1791 // If either of the constants are nans, then the whole thing returns
1792 // true.
1793 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +00001794 return Builder.getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001795
Chris Lattner0a8191e2010-01-05 07:50:36 +00001796 // Otherwise, no need to compare the two constants, compare the
1797 // rest.
Craig Topperbb4069e2017-07-07 23:16:26 +00001798 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001800
Chris Lattner0a8191e2010-01-05 07:50:36 +00001801 // Handle vector zeros. This occurs because the canonical form of
1802 // "fcmp uno x,x" is "fcmp uno x, 0".
1803 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1804 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +00001805 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001806
Craig Topperf40110f2014-04-25 05:29:35 +00001807 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001808 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001809
Craig Topperf40110f2014-04-25 05:29:35 +00001810 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811}
1812
Sanjay Patel18549272015-09-08 18:24:36 +00001813/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001814///
1815/// ((A | B) & C1) | (B & C2)
1816///
1817/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001818///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001819/// (A & C1) | B
1820///
1821/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001822static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1823 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001824 InstCombiner::BuilderTy &Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001825 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001826 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827
Craig Topperf40110f2014-04-25 05:29:35 +00001828 Value *V1 = nullptr;
1829 ConstantInt *CI2 = nullptr;
1830 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831
1832 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001833 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834
1835 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001836 Value *NewOp = Builder.CreateAnd((V1 == A) ? B : A, CI1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001837 return BinaryOperator::CreateOr(NewOp, V1);
1838 }
1839
Craig Topperf40110f2014-04-25 05:29:35 +00001840 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001841}
1842
David Majnemer5d1aeba2014-08-21 05:14:48 +00001843/// \brief This helper function folds:
1844///
Craig Toppera074c102017-06-21 18:57:00 +00001845/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001846///
1847/// into:
1848///
1849/// (A & C1) ^ B
1850///
1851/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001852static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1853 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001854 InstCombiner::BuilderTy &Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001855 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1856 if (!CI1)
1857 return nullptr;
1858
1859 Value *V1 = nullptr;
1860 ConstantInt *CI2 = nullptr;
1861 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1862 return nullptr;
1863
1864 APInt Xor = CI1->getValue() ^ CI2->getValue();
1865 if (!Xor.isAllOnesValue())
1866 return nullptr;
1867
1868 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001869 Value *NewOp = Builder.CreateAnd(V1 == A ? B : A, CI1);
David Majnemer5d1aeba2014-08-21 05:14:48 +00001870 return BinaryOperator::CreateXor(NewOp, V1);
1871 }
1872
1873 return nullptr;
1874}
1875
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001876// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1877// here. We should standardize that construct where it is needed or choose some
1878// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001879Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001880 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1882
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001883 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001884 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001885
Craig Toppera4205622017-06-09 03:21:29 +00001886 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001887 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001888
Craig Topper9d4171a2012-12-20 07:09:41 +00001889 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001890 // purpose is to compute bits we don't care about.
1891 if (SimplifyDemandedInstructionBits(I))
1892 return &I;
1893
Sanjay Patele0c26e02017-04-23 22:00:02 +00001894 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001895 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001896 return Xor;
1897
1898 // (A&B)|(A&C) -> A&(B|C) etc
1899 if (Value *V = SimplifyUsingDistributiveLaws(I))
1900 return replaceInstUsesWith(I, V);
1901
Craig Topper95e41422017-07-06 16:24:23 +00001902 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001903 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001904
Craig Topper86173602017-04-04 20:26:25 +00001905 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001906 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1907 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908
Chad Rosiere5819e22016-05-26 14:58:51 +00001909 // Given an OR instruction, check to see if this is a bswap.
1910 if (Instruction *BSwap = MatchBSwap(I))
1911 return BSwap;
1912
Craig Topperafa07c52017-04-09 06:12:41 +00001913 {
1914 Value *A;
1915 const APInt *C;
1916 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1917 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1918 MaskedValueIsZero(Op1, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001919 Value *NOr = Builder.CreateOr(A, Op1);
Craig Topperafa07c52017-04-09 06:12:41 +00001920 NOr->takeName(Op0);
1921 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001922 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001923 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001924
Craig Topperafa07c52017-04-09 06:12:41 +00001925 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1926 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1927 MaskedValueIsZero(Op0, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001928 Value *NOr = Builder.CreateOr(A, Op0);
Craig Topperafa07c52017-04-09 06:12:41 +00001929 NOr->takeName(Op0);
1930 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001931 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001932 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001933 }
1934
Craig Topperafa07c52017-04-09 06:12:41 +00001935 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001936
1937 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00001938 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001939 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1940 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00001941 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00001942 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1943 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001944 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00001945 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00001946 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001947 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001948 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001949 ((V1 == B &&
1950 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
1951 (V2 == B &&
1952 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001953 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00001954 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001955 // Or commutes, try both ways.
1956 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001957 ((V1 == A &&
1958 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
1959 (V2 == A &&
1960 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001961 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00001962 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001963
Chris Lattner95188692010-01-11 06:55:24 +00001964 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001965 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00001966 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00001967 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001968 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00001969 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001970 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001971 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00001972 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00001973 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001974 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001975 }
1976 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001978 // Don't try to form a select if it's unlikely that we'll get rid of at
1979 // least one of the operands. A select is generally more expensive than the
1980 // 'or' that it is replacing.
1981 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1982 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Craig Topperbb4069e2017-07-07 23:16:26 +00001983 if (Value *V = matchSelectFromAndOr(A, C, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001984 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001985 if (Value *V = matchSelectFromAndOr(A, C, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001986 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001987 if (Value *V = matchSelectFromAndOr(C, A, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001988 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001989 if (Value *V = matchSelectFromAndOr(C, A, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001990 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001991 if (Value *V = matchSelectFromAndOr(B, D, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001992 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001993 if (Value *V = matchSelectFromAndOr(B, D, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001994 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001995 if (Value *V = matchSelectFromAndOr(D, B, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001996 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001997 if (Value *V = matchSelectFromAndOr(D, B, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001998 return replaceInstUsesWith(I, V);
1999 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002000
Benjamin Kramer11743242010-07-12 13:34:22 +00002001 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002002 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2003 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2004 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002005 }
2006 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002007 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2008 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2009 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002010 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002011 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002012 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2013 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2014 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002015 }
2016 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002017 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2018 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2019 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002020 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002021 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002022
David Majnemer42af3602014-07-30 21:26:37 +00002023 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2024 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2025 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002026 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002027
2028 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2029 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2030 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002031 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002032
David Majnemerf1eda232014-08-14 06:41:38 +00002033 // ((B | C) & A) | B -> B | (A & C)
2034 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002035 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00002036
Craig Topperbb4069e2017-07-07 23:16:26 +00002037 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002038 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002039
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002040 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002041 bool SwappedForXor = false;
2042 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002043 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002044 SwappedForXor = true;
2045 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002046
2047 // A | ( A ^ B) -> A | B
2048 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002049 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002050 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2051 if (Op0 == A || Op0 == B)
2052 return BinaryOperator::CreateOr(A, B);
2053
Chad Rosier7813dce2012-04-26 23:29:14 +00002054 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2055 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2056 return BinaryOperator::CreateOr(A, B);
2057
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002058 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002059 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002060 return BinaryOperator::CreateOr(Not, Op0);
2061 }
2062 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002063 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002064 return BinaryOperator::CreateOr(Not, Op0);
2065 }
2066 }
2067
2068 // A | ~(A | B) -> A | ~B
2069 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002070 if (match(Op1, m_Not(m_Value(A))))
2071 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002072 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2073 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2074 B->getOpcode() == Instruction::Xor)) {
2075 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2076 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002077 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002078 return BinaryOperator::CreateOr(Not, Op0);
2079 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002080
Eli Friedmane06535b2012-03-16 00:52:42 +00002081 if (SwappedForXor)
2082 std::swap(Op0, Op1);
2083
David Majnemer3d6f80b2014-11-28 19:58:29 +00002084 {
2085 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2086 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2087 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002088 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002089 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002090
David Majnemer3d6f80b2014-11-28 19:58:29 +00002091 // TODO: Make this recursive; it's a little tricky because an arbitrary
2092 // number of 'or' instructions might have to be created.
2093 Value *X, *Y;
2094 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2095 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002096 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002097 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002098 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002099 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002100 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002101 }
2102 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2103 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002104 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002105 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002106 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002107 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002108 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002109 }
2110 }
2111
Chris Lattner4e8137d2010-02-11 06:26:33 +00002112 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2113 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2114 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002115 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002116 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002117
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002118 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2119 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002120
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002121 // 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 +00002122 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002123 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002124 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002125 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002126 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002127 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2128
Owen Andersonc237a842010-09-13 17:59:27 +00002129 // Note: If we've gotten to the point of visiting the outer OR, then the
2130 // inner one couldn't be simplified. If it was a constant, then it won't
2131 // be simplified by a later pass either, so we try swapping the inner/outer
2132 // ORs in the hopes that we'll be able to simplify it this way.
2133 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002134 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002135 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2136 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002137 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002138 Inner->takeName(Op0);
2139 return BinaryOperator::CreateOr(Inner, C1);
2140 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002141
Bill Wendling23242092013-02-16 23:41:36 +00002142 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2143 // Since this OR statement hasn't been optimized further yet, we hope
2144 // that this transformation will allow the new ORs to be optimized.
2145 {
Craig Topperf40110f2014-04-25 05:29:35 +00002146 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002147 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2148 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2149 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002150 Value *orTrue = Builder.CreateOr(A, C);
2151 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002152 return SelectInst::Create(X, orTrue, orFalse);
2153 }
2154 }
2155
Craig Topperf40110f2014-04-25 05:29:35 +00002156 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002157}
2158
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002159/// A ^ B can be specified using other logic ops in a variety of patterns. We
2160/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002161static Instruction *foldXorToXor(BinaryOperator &I,
2162 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002163 assert(I.getOpcode() == Instruction::Xor);
2164 Value *Op0 = I.getOperand(0);
2165 Value *Op1 = I.getOperand(1);
2166 Value *A, *B;
2167
2168 // There are 4 commuted variants for each of the basic patterns.
2169
2170 // (A & B) ^ (A | B) -> A ^ B
2171 // (A & B) ^ (B | A) -> A ^ B
2172 // (A | B) ^ (A & B) -> A ^ B
2173 // (A | B) ^ (B & A) -> A ^ B
2174 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2175 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2176 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2177 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2178 I.setOperand(0, A);
2179 I.setOperand(1, B);
2180 return &I;
2181 }
2182
2183 // (A | ~B) ^ (~A | B) -> A ^ B
2184 // (~B | A) ^ (~A | B) -> A ^ B
2185 // (~A | B) ^ (A | ~B) -> A ^ B
2186 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002187 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2188 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2189 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2190 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002191 I.setOperand(0, A);
2192 I.setOperand(1, B);
2193 return &I;
2194 }
2195
2196 // (A & ~B) ^ (~A & B) -> A ^ B
2197 // (~B & A) ^ (~A & B) -> A ^ B
2198 // (~A & B) ^ (A & ~B) -> A ^ B
2199 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002200 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2201 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2202 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2203 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002204 I.setOperand(0, A);
2205 I.setOperand(1, B);
2206 return &I;
2207 }
2208
Craig Topperf60ab472017-07-02 01:15:51 +00002209 // For the remaining cases we need to get rid of one of the operands.
2210 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2211 return nullptr;
2212
2213 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2214 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2215 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2216 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2217 // Complexity sorting ensures the not will be on the right side.
2218 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2219 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2220 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2221 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2222 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2223
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002224 return nullptr;
2225}
2226
Sanjay Patel5e456b92017-05-18 20:53:16 +00002227Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2228 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2229 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2230 LHS->getOperand(1) == RHS->getOperand(0))
2231 LHS->swapOperands();
2232 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2233 LHS->getOperand(1) == RHS->getOperand(1)) {
2234 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2235 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2236 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2237 bool isSigned = LHS->isSigned() || RHS->isSigned();
2238 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2239 }
2240 }
2241
Sanjay Pateladca8252017-06-20 12:40:55 +00002242 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2243 // into those logic ops. That is, try to turn this into an and-of-icmps
2244 // because we have many folds for that pattern.
2245 //
2246 // This is based on a truth table definition of xor:
2247 // X ^ Y --> (X | Y) & !(X & Y)
2248 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2249 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2250 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2251 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2252 // TODO: Independently handle cases where the 'and' side is a constant.
2253 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2254 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2255 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002256 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002257 }
2258 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002259 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002260 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002261 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002262 }
2263 }
2264 }
2265
Sanjay Patel5e456b92017-05-18 20:53:16 +00002266 return nullptr;
2267}
2268
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002269// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2270// here. We should standardize that construct where it is needed or choose some
2271// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002272Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002273 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002276 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002277 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002278
Craig Toppera4205622017-06-09 03:21:29 +00002279 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002280 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002281
Craig Topperbb4069e2017-07-07 23:16:26 +00002282 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002283 return NewXor;
2284
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002285 // (A&B)^(A&C) -> A&(B^C) etc
2286 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002287 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002288
Craig Topper9d4171a2012-12-20 07:09:41 +00002289 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002290 // purpose is to compute bits we don't care about.
2291 if (SimplifyDemandedInstructionBits(I))
2292 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002293
Craig Topper95e41422017-07-06 16:24:23 +00002294 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002295 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002296
Sanjay Patel6381db12017-05-02 15:31:40 +00002297 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2298 Value *X, *Y;
2299
2300 // We must eliminate the and/or (one-use) for these transforms to not increase
2301 // the instruction count.
2302 // ~(~X & Y) --> (X | ~Y)
2303 // ~(Y & ~X) --> (X | ~Y)
2304 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 +00002305 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002306 return BinaryOperator::CreateOr(X, NotY);
2307 }
2308 // ~(~X | Y) --> (X & ~Y)
2309 // ~(Y | ~X) --> (X & ~Y)
2310 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 +00002311 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002312 return BinaryOperator::CreateAnd(X, NotY);
2313 }
2314
Sanjay Patel3b863f82017-04-22 18:05:35 +00002315 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002316 BinaryOperator *NotVal;
2317 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2318 if (NotVal->getOpcode() == Instruction::And ||
2319 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002320 // Apply DeMorgan's Law when inverts are free:
2321 // ~(X & Y) --> (~X | ~Y)
2322 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002323 if (IsFreeToInvert(NotVal->getOperand(0),
2324 NotVal->getOperand(0)->hasOneUse()) &&
2325 IsFreeToInvert(NotVal->getOperand(1),
2326 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002327 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2328 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002329 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002330 return BinaryOperator::CreateOr(NotX, NotY);
2331 return BinaryOperator::CreateAnd(NotX, NotY);
2332 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002333 }
2334
2335 // ~(~X >>s Y) --> (X >>s Y)
2336 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2337 return BinaryOperator::CreateAShr(X, Y);
2338
2339 // If we are inverting a right-shifted constant, we may be able to eliminate
2340 // the 'not' by inverting the constant and using the opposite shift type.
2341 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2342 // but we must check that in case that transform has not fired yet.
2343 const APInt *C;
2344 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2345 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2346 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2347 return BinaryOperator::CreateLShr(NotC, Y);
2348 }
2349
2350 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2351 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2352 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2353 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002354 }
2355 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002356
Craig Topper798a19a2017-06-29 00:07:08 +00002357 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002358 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002359 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002360 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2361 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002362 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002363
Craig Topperb5bf0162017-08-06 06:28:41 +00002364 {
2365 const APInt *RHSC;
2366 if (match(Op1, m_APInt(RHSC))) {
2367 Value *V;
2368 const APInt *C;
2369 if (match(Op0, m_Sub(m_APInt(C), m_Value(V)))) {
2370 // ~(c-X) == X-c-1 == X+(-c-1)
2371 if (RHSC->isAllOnesValue()) {
2372 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2373 return BinaryOperator::CreateAdd(V, NewC);
2374 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002375 if (RHSC->isSignMask()) {
2376 // (C - X) ^ signmask -> (C + signmask - X)
2377 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2378 return BinaryOperator::CreateSub(NewC, V);
2379 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002380 } else if (match(Op0, m_Add(m_Value(V), m_APInt(C)))) {
2381 // ~(X-c) --> (-c-1)-X
2382 if (RHSC->isAllOnesValue()) {
2383 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2384 return BinaryOperator::CreateSub(NewC, V);
2385 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002386 if (RHSC->isSignMask()) {
2387 // (X + C) ^ signmask -> (X + C + signmask)
2388 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2389 return BinaryOperator::CreateAdd(V, NewC);
2390 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002391 }
2392 }
2393 }
2394
Craig Topper9d1821b2017-04-09 06:12:31 +00002395 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002396 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002397 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9cbdbef2017-08-06 22:17:21 +00002398 if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002399 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002400 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2401 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002402 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002403 // Anything in both C1 and C2 is known to be zero, remove it from
2404 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002405 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002406 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002407 ConstantExpr::getNot(CommonBits));
2408 Worklist.Add(Op0I);
2409 I.setOperand(0, Op0I->getOperand(0));
2410 I.setOperand(1, NewRHS);
2411 return &I;
2412 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002413 } else if (Op0I->getOpcode() == Instruction::LShr) {
2414 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2415 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002416 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002417 ConstantInt *C1;
2418 if (Op0I->hasOneUse() &&
2419 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2420 E1->getOpcode() == Instruction::Xor &&
2421 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2422 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002423 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002424 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2425 FoldConst ^= C3->getValue();
2426 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002427 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002428 Opnd0->takeName(Op0I);
2429 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2430 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2431
2432 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2433 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002434 }
2435 }
2436 }
Craig Topper86173602017-04-04 20:26:25 +00002437 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002438
Craig Topper86173602017-04-04 20:26:25 +00002439 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002440 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2441 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002442
Craig Topper76394602017-04-10 06:53:23 +00002443 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002445 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002446 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002447 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002448 std::swap(A, B);
2449 }
2450 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002451 I.swapOperands(); // Simplified below.
2452 std::swap(Op0, Op1);
2453 }
Craig Topper76394602017-04-10 06:53:23 +00002454 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002455 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002456 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002457 std::swap(A, B);
2458 }
2459 if (B == Op0) { // A^(B&A) -> (B&A)^A
2460 I.swapOperands(); // Simplified below.
2461 std::swap(Op0, Op1);
2462 }
2463 }
2464 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002465
Craig Topper76394602017-04-10 06:53:23 +00002466 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002467 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002468 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002469 if (A == Op1) // (B|A)^B == (A|B)^B
2470 std::swap(A, B);
2471 if (B == Op1) // (A|B)^B == A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00002472 return BinaryOperator::CreateAnd(A, Builder.CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002473 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002474 if (A == Op1) // (A&B)^A -> (B&A)^A
2475 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002476 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002477 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002478 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Craig Topperbb4069e2017-07-07 23:16:26 +00002479 return BinaryOperator::CreateAnd(Builder.CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002480 }
2481 }
2482 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002483
Craig Topper76394602017-04-10 06:53:23 +00002484 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002485 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002486 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002487 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2488 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002489 if (D == A)
2490 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002491 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002492 if (D == B)
2493 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002494 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002495 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002496 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002497 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2498 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002499 if (D == A)
2500 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002501 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002502 if (D == B)
2503 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002504 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002505 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002506 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002507 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002508 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002509 return BinaryOperator::CreateOr(A, B);
2510 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002511 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002512 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002513 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002514 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002515
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002516 // (A & ~B) ^ ~A -> ~(A & B)
2517 // (~B & A) ^ ~A -> ~(A & B)
2518 Value *A, *B;
2519 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002520 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002521 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002522
Sanjay Patel5e456b92017-05-18 20:53:16 +00002523 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2524 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2525 if (Value *V = foldXorOfICmps(LHS, RHS))
2526 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002527
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002528 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2529 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002530
Craig Topperf40110f2014-04-25 05:29:35 +00002531 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002532}