blob: a8e2aaaa81b76be2163893026daa527955a27bd5 [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
14#include "InstCombine.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"
Chris Lattner0a8191e2010-01-05 07:50:36 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chris Lattner0a8191e2010-01-05 07:50:36 +000025/// isFreeToInvert - Return true if the specified value is free to invert (apply
26/// ~ to). This happens in cases where the ~ can be eliminated.
27static inline bool isFreeToInvert(Value *V) {
28 // ~(~(X)) -> X.
29 if (BinaryOperator::isNot(V))
30 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000031
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 // Constants can be considered to be not'ed values.
33 if (isa<ConstantInt>(V))
34 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000035
Chris Lattner0a8191e2010-01-05 07:50:36 +000036 // Compares can be inverted if they have a single use.
37 if (CmpInst *CI = dyn_cast<CmpInst>(V))
38 return CI->hasOneUse();
Craig Topper9d4171a2012-12-20 07:09:41 +000039
Chris Lattner0a8191e2010-01-05 07:50:36 +000040 return false;
41}
42
43static inline Value *dyn_castNotVal(Value *V) {
44 // If this is not(not(x)) don't return that this is a not: we want the two
45 // not's to be folded first.
46 if (BinaryOperator::isNot(V)) {
47 Value *Operand = BinaryOperator::getNotArgument(V);
48 if (!isFreeToInvert(Operand))
49 return Operand;
50 }
Craig Topper9d4171a2012-12-20 07:09:41 +000051
Chris Lattner0a8191e2010-01-05 07:50:36 +000052 // Constants can be considered to be not'ed values...
53 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
54 return ConstantInt::get(C->getType(), ~C->getValue());
55 return 0;
56}
57
Chris Lattner0a8191e2010-01-05 07:50:36 +000058/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
59/// predicate into a three bit mask. It also returns whether it is an ordered
60/// predicate by reference.
61static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
62 isOrdered = false;
63 switch (CC) {
64 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
65 case FCmpInst::FCMP_UNO: return 0; // 000
66 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
67 case FCmpInst::FCMP_UGT: return 1; // 001
68 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
69 case FCmpInst::FCMP_UEQ: return 2; // 010
70 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
71 case FCmpInst::FCMP_UGE: return 3; // 011
72 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
73 case FCmpInst::FCMP_ULT: return 4; // 100
74 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
75 case FCmpInst::FCMP_UNE: return 5; // 101
76 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
77 case FCmpInst::FCMP_ULE: return 6; // 110
78 // True -> 7
79 default:
80 // Not expecting FCMP_FALSE and FCMP_TRUE;
81 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000082 }
83}
84
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000085/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000086/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000087/// new ICmp instruction. The sign is passed in to determine which kind
88/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000089static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
90 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000091 ICmpInst::Predicate NewPred;
92 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
93 return NewConstant;
94 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000095}
96
97/// getFCmpValue - This is the complement of getFCmpCode, which turns an
98/// opcode and two operands into either a FCmp instruction. isordered is passed
99/// in to determine which kind of predicate to use in the new fcmp instruction.
100static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000101 Value *LHS, Value *RHS,
102 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000103 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000104 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +0000105 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000106 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
107 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
108 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
109 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
110 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
111 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
112 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +0000113 case 7:
Owen Andersona8342002011-01-21 19:39:42 +0000114 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
115 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000116 }
Chris Lattner067459c2010-03-05 08:46:26 +0000117 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000118}
119
Chris Lattner0a8191e2010-01-05 07:50:36 +0000120// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
121// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
122// guaranteed to be a binary operator.
123Instruction *InstCombiner::OptAndOp(Instruction *Op,
124 ConstantInt *OpRHS,
125 ConstantInt *AndRHS,
126 BinaryOperator &TheAnd) {
127 Value *X = Op->getOperand(0);
128 Constant *Together = 0;
129 if (!Op->isShift())
130 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
131
132 switch (Op->getOpcode()) {
133 case Instruction::Xor:
134 if (Op->hasOneUse()) {
135 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
136 Value *And = Builder->CreateAnd(X, AndRHS);
137 And->takeName(Op);
138 return BinaryOperator::CreateXor(And, Together);
139 }
140 break;
141 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000142 if (Op->hasOneUse()){
143 if (Together != OpRHS) {
144 // (X | C1) & C2 --> (X | (C1&C2)) & C2
145 Value *Or = Builder->CreateOr(X, Together);
146 Or->takeName(Op);
147 return BinaryOperator::CreateAnd(Or, AndRHS);
148 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000149
Owen Andersonc237a842010-09-13 17:59:27 +0000150 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
151 if (TogetherCI && !TogetherCI->isZero()){
152 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
153 // NOTE: This reduces the number of bits set in the & mask, which
154 // can expose opportunities for store narrowing.
155 Together = ConstantExpr::getXor(AndRHS, Together);
156 Value *And = Builder->CreateAnd(X, Together);
157 And->takeName(Op);
158 return BinaryOperator::CreateOr(And, OpRHS);
159 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000160 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000161
Chris Lattner0a8191e2010-01-05 07:50:36 +0000162 break;
163 case Instruction::Add:
164 if (Op->hasOneUse()) {
165 // Adding a one to a single bit bit-field should be turned into an XOR
166 // of the bit. First thing to check is to see if this AND is with a
167 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000168 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000169
170 // If there is only one bit set.
171 if (AndRHSV.isPowerOf2()) {
172 // Ok, at this point, we know that we are masking the result of the
173 // ADD down to exactly one bit. If the constant we are adding has
174 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000175 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000176
177 // Check to see if any bits below the one bit set in AndRHSV are set.
178 if ((AddRHS & (AndRHSV-1)) == 0) {
179 // If not, the only thing that can effect the output of the AND is
180 // the bit specified by AndRHSV. If that bit is set, the effect of
181 // the XOR is to toggle the bit. If it is clear, then the ADD has
182 // no effect.
183 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
184 TheAnd.setOperand(0, X);
185 return &TheAnd;
186 } else {
187 // Pull the XOR out of the AND.
188 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
189 NewAnd->takeName(Op);
190 return BinaryOperator::CreateXor(NewAnd, AndRHS);
191 }
192 }
193 }
194 }
195 break;
196
197 case Instruction::Shl: {
198 // We know that the AND will not produce any of the bits shifted in, so if
199 // the anded constant includes them, clear them now!
200 //
201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
203 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000204 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000205
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000206 if (CI->getValue() == ShlMask)
207 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000209
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000210 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000211 TheAnd.setOperand(1, CI);
212 return &TheAnd;
213 }
214 break;
215 }
216 case Instruction::LShr: {
217 // We know that the AND will not produce any of the bits shifted in, so if
218 // the anded constant includes them, clear them now! This only applies to
219 // unsigned shifts, because a signed shr may bring in set bits!
220 //
221 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
222 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
223 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000224 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000225
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000226 if (CI->getValue() == ShrMask)
227 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000228 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000229
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000230 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000231 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
232 return &TheAnd;
233 }
234 break;
235 }
236 case Instruction::AShr:
237 // Signed shr.
238 // See if this is shifting in some sign extension, then masking it out
239 // with an and.
240 if (Op->hasOneUse()) {
241 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
242 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
243 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000244 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000245 if (C == AndRHS) { // Masking out bits shifted in.
246 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
247 // Make the argument unsigned.
248 Value *ShVal = Op->getOperand(0);
249 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
250 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
251 }
252 }
253 break;
254 }
255 return 0;
256}
257
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000258/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
259/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000260/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000261/// whether to treat the V, Lo and HI as signed or not. IB is the location to
262/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000263Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
264 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000265 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000266 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
267 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000268
Chris Lattner0a8191e2010-01-05 07:50:36 +0000269 if (Inside) {
270 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000271 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000272
273 // V >= Min && V < Hi --> V < Hi
274 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000275 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000276 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000277 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000278 }
279
280 // Emit V-Lo <u Hi-Lo
281 Constant *NegLo = ConstantExpr::getNeg(Lo);
282 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
283 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000284 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000285 }
286
287 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000288 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000289
290 // V < Min || V >= Hi -> V > Hi-1
291 Hi = SubOne(cast<ConstantInt>(Hi));
292 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000293 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000294 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000295 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000296 }
297
298 // Emit V-Lo >u Hi-1-Lo
299 // Note that Hi has already had one subtracted from it, above.
300 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
301 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
302 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000303 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000304}
305
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000306// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000307// any number of 0s on either side. The 1s are allowed to wrap from LSB to
308// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
309// not, since all 1s are not contiguous.
310static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
311 const APInt& V = Val->getValue();
312 uint32_t BitWidth = Val->getType()->getBitWidth();
313 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
314
315 // look for the first zero bit after the run of ones
316 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
317 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000318 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000319 return true;
320}
321
322/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
323/// where isSub determines whether the operator is a sub. If we can fold one of
324/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000325///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000326/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
327/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
328/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000329///
330/// return (A +/- B).
331///
332Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
333 ConstantInt *Mask, bool isSub,
334 Instruction &I) {
335 Instruction *LHSI = dyn_cast<Instruction>(LHS);
336 if (!LHSI || LHSI->getNumOperands() != 2 ||
337 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
338
339 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
340
341 switch (LHSI->getOpcode()) {
342 default: return 0;
343 case Instruction::And:
344 if (ConstantExpr::getAnd(N, Mask) == Mask) {
345 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000346 if ((Mask->getValue().countLeadingZeros() +
347 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000348 Mask->getValue().getBitWidth())
349 break;
350
351 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
352 // part, we don't need any explicit masks to take them out of A. If that
353 // is all N is, ignore it.
354 uint32_t MB = 0, ME = 0;
355 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
356 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
357 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
358 if (MaskedValueIsZero(RHS, Mask))
359 break;
360 }
361 }
362 return 0;
363 case Instruction::Or:
364 case Instruction::Xor:
365 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000366 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000367 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
368 && ConstantExpr::getAnd(N, Mask)->isNullValue())
369 break;
370 return 0;
371 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000372
Chris Lattner0a8191e2010-01-05 07:50:36 +0000373 if (isSub)
374 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
375 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
376}
377
Owen Anderson3fe002d2010-09-08 22:16:17 +0000378/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000379/// One of A and B is considered the mask, the other the value. This is
380/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000381/// contains only "Mask", then both A and B can be considered masks.
382/// If A is the mask, then it was proven, that (A & C) == C. This
383/// is trivial if C == A, or C == 0. If both A and C are constants, this
384/// proof is also easy.
385/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000386/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000387/// if (A & B) == A, or all bits of A are set in B.
388/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000389/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000390/// if (A & B) == 0, or all bits of A are cleared in B.
391/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000392/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000393/// contain any number of one bits and zero bits.
394/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
395/// The Part "Not" means, that in above descriptions "==" should be replaced
396/// by "!=".
397/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
398/// If the mask A contains a single bit, then the following is equivalent:
399/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
400/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
401enum MaskedICmpType {
402 FoldMskICmp_AMask_AllOnes = 1,
403 FoldMskICmp_AMask_NotAllOnes = 2,
404 FoldMskICmp_BMask_AllOnes = 4,
405 FoldMskICmp_BMask_NotAllOnes = 8,
406 FoldMskICmp_Mask_AllZeroes = 16,
407 FoldMskICmp_Mask_NotAllZeroes = 32,
408 FoldMskICmp_AMask_Mixed = 64,
409 FoldMskICmp_AMask_NotMixed = 128,
410 FoldMskICmp_BMask_Mixed = 256,
411 FoldMskICmp_BMask_NotMixed = 512
412};
413
414/// return the set of pattern classes (from MaskedICmpType)
415/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000416static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000417 ICmpInst::Predicate SCC)
418{
419 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
420 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
421 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
422 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topper9d4171a2012-12-20 07:09:41 +0000423 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 ACst->getValue().isPowerOf2());
Craig Topper9d4171a2012-12-20 07:09:41 +0000425 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000426 BCst->getValue().isPowerOf2());
427 unsigned result = 0;
428 if (CCst != 0 && CCst->isZero()) {
429 // if C is zero, then both A and B qualify as mask
430 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
431 FoldMskICmp_Mask_AllZeroes |
432 FoldMskICmp_AMask_Mixed |
433 FoldMskICmp_BMask_Mixed)
434 : (FoldMskICmp_Mask_NotAllZeroes |
435 FoldMskICmp_Mask_NotAllZeroes |
436 FoldMskICmp_AMask_NotMixed |
437 FoldMskICmp_BMask_NotMixed));
438 if (icmp_abit)
439 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000440 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000441 : (FoldMskICmp_AMask_AllOnes |
442 FoldMskICmp_AMask_Mixed));
443 if (icmp_bbit)
444 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000445 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000446 : (FoldMskICmp_BMask_AllOnes |
447 FoldMskICmp_BMask_Mixed));
448 return result;
449 }
450 if (A == C) {
451 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
452 FoldMskICmp_AMask_Mixed)
453 : (FoldMskICmp_AMask_NotAllOnes |
454 FoldMskICmp_AMask_NotMixed));
455 if (icmp_abit)
456 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
457 FoldMskICmp_AMask_NotMixed)
458 : (FoldMskICmp_Mask_AllZeroes |
459 FoldMskICmp_AMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000460 } else if (ACst != 0 && CCst != 0 &&
461 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000462 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
463 : FoldMskICmp_AMask_NotMixed);
464 }
Craig Topperae48cb22012-12-20 07:15:54 +0000465 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
467 FoldMskICmp_BMask_Mixed)
468 : (FoldMskICmp_BMask_NotAllOnes |
469 FoldMskICmp_BMask_NotMixed));
470 if (icmp_bbit)
471 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000472 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000473 : (FoldMskICmp_Mask_AllZeroes |
474 FoldMskICmp_BMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000475 } else if (BCst != 0 && CCst != 0 &&
476 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000477 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
478 : FoldMskICmp_BMask_NotMixed);
479 }
480 return result;
481}
482
Tim Northoverc0756c42013-09-04 11:57:13 +0000483/// Convert an analysis of a masked ICmp into its equivalent if all boolean
484/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
485/// is adjacent to the corresponding normal flag (recording ==), this just
486/// involves swapping those bits over.
487static unsigned conjugateICmpMask(unsigned Mask) {
488 unsigned NewMask;
489 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
490 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
491 FoldMskICmp_BMask_Mixed))
492 << 1;
493
494 NewMask |=
495 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
496 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
497 FoldMskICmp_BMask_NotMixed))
498 >> 1;
499
500 return NewMask;
501}
502
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000503/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
504/// if possible. The returned predicate is either == or !=. Returns false if
505/// decomposition fails.
506static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
507 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000508 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
509 if (!C)
510 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000511
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000512 switch (I->getPredicate()) {
513 default:
514 return false;
515 case ICmpInst::ICMP_SLT:
516 // X < 0 is equivalent to (X & SignBit) != 0.
517 if (!C->isZero())
518 return false;
519 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
520 Pred = ICmpInst::ICMP_NE;
521 break;
522 case ICmpInst::ICMP_SGT:
523 // X > -1 is equivalent to (X & SignBit) == 0.
524 if (!C->isAllOnesValue())
525 return false;
526 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
527 Pred = ICmpInst::ICMP_EQ;
528 break;
529 case ICmpInst::ICMP_ULT:
530 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
531 if (!C->getValue().isPowerOf2())
532 return false;
533 Y = ConstantInt::get(I->getContext(), -C->getValue());
534 Pred = ICmpInst::ICMP_EQ;
535 break;
536 case ICmpInst::ICMP_UGT:
537 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
538 if (!(C->getValue() + 1).isPowerOf2())
539 return false;
540 Y = ConstantInt::get(I->getContext(), ~C->getValue());
541 Pred = ICmpInst::ICMP_NE;
542 break;
543 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000544
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000545 X = I->getOperand(0);
546 Z = ConstantInt::getNullValue(C->getType());
547 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000548}
549
Owen Anderson3fe002d2010-09-08 22:16:17 +0000550/// foldLogOpOfMaskedICmpsHelper:
551/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
552/// return the set of pattern classes (from MaskedICmpType)
553/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000554static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000555 Value*& B, Value*& C,
556 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000557 ICmpInst *LHS, ICmpInst *RHS,
558 ICmpInst::Predicate &LHSCC,
559 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
561 // vectors are not (yet?) supported
562 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
563
564 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000565 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000566 // and L11 & L12 == L21 & L22. The same goes for RHS.
567 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000568 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000569 // above.
570 Value *L1 = LHS->getOperand(0);
571 Value *L2 = LHS->getOperand(1);
572 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000573 // Check whether the icmp can be decomposed into a bit test.
574 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
575 L21 = L22 = L1 = 0;
576 } else {
577 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000578 if (!L1->getType()->isIntegerTy()) {
579 // You can icmp pointers, for example. They really aren't masks.
580 L11 = L12 = 0;
581 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
582 // Any icmp can be viewed as being trivially masked; if it allows us to
583 // remove one, it's worth it.
584 L11 = L1;
585 L12 = Constant::getAllOnesValue(L1->getType());
586 }
587
588 if (!L2->getType()->isIntegerTy()) {
589 // You can icmp pointers, for example. They really aren't masks.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000590 L21 = L22 = 0;
Tim Northoverdc647a22013-09-04 11:57:17 +0000591 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
592 L21 = L2;
593 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000594 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000595 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000596
597 // Bail if LHS was a icmp that can't be decomposed into an equality.
598 if (!ICmpInst::isEquality(LHSCC))
599 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000600
601 Value *R1 = RHS->getOperand(0);
602 Value *R2 = RHS->getOperand(1);
603 Value *R11,*R12;
604 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000605 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
606 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
607 A = R11; D = R12;
608 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
609 A = R12; D = R11;
610 } else {
611 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000612 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000613 E = R2; R1 = 0; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000614 } else if (R1->getType()->isIntegerTy()) {
615 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
616 // As before, model no mask as a trivial mask if it'll let us do an
617 // optimisation.
618 R11 = R1;
619 R12 = Constant::getAllOnesValue(R1->getType());
620 }
621
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000622 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
623 A = R11; D = R12; E = R2; ok = true;
624 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000625 A = R12; D = R11; E = R2; ok = true;
626 }
627 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000628
629 // Bail if RHS was a icmp that can't be decomposed into an equality.
630 if (!ICmpInst::isEquality(RHSCC))
631 return 0;
632
633 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000634 if (!ok && R2->getType()->isIntegerTy()) {
635 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
636 R11 = R2;
637 R12 = Constant::getAllOnesValue(R2->getType());
638 }
639
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000640 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
641 A = R11; D = R12; E = R1; ok = true;
642 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000643 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000644 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000645 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000646 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000647 }
648 if (!ok)
649 return 0;
650
651 if (L11 == A) {
652 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000653 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000654 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000655 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000656 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000657 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000658 B = L21; C = L1;
659 }
660
661 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
662 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
663 return left_type & right_type;
664}
665/// foldLogOpOfMaskedICmps:
666/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
667/// into a single (icmp(A & X) ==/!= Y)
Tim Northoverc0756c42013-09-04 11:57:13 +0000668static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000669 llvm::InstCombiner::BuilderTy* Builder) {
670 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000671 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
672 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
673 LHSCC, RHSCC);
Benjamin Kramerf7fe24f2012-01-09 17:36:29 +0000674 if (mask == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000675 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
676 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000677
Tim Northoverc0756c42013-09-04 11:57:13 +0000678 // In full generality:
679 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
680 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
681 //
682 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
683 // equivalent to (icmp (A & X) !Op Y).
684 //
685 // Therefore, we can pretend for the rest of this function that we're dealing
686 // with the conjunction, provided we flip the sense of any comparisons (both
687 // input and output).
688
689 // In most cases we're going to produce an EQ for the "&&" case.
690 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
691 if (!IsAnd) {
692 // Convert the masking analysis into its equivalent with negated
693 // comparisons.
694 mask = conjugateICmpMask(mask);
695 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000696
697 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000698 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000699 // -> (icmp eq (A & (B|D)), 0)
700 Value* newOr = Builder->CreateOr(B, D);
701 Value* newAnd = Builder->CreateAnd(A, newOr);
702 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000703 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000704 // with B and D, having a single bit set
705 Value* zero = Constant::getNullValue(A->getType());
706 return Builder->CreateICmp(NEWCC, newAnd, zero);
707 }
Craig Topperae48cb22012-12-20 07:15:54 +0000708 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000709 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000710 // -> (icmp eq (A & (B|D)), (B|D))
711 Value* newOr = Builder->CreateOr(B, D);
712 Value* newAnd = Builder->CreateAnd(A, newOr);
713 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000714 }
Craig Topperae48cb22012-12-20 07:15:54 +0000715 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000716 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000717 // -> (icmp eq (A & (B&D)), A)
718 Value* newAnd1 = Builder->CreateAnd(B, D);
719 Value* newAnd = Builder->CreateAnd(A, newAnd1);
720 return Builder->CreateICmp(NEWCC, newAnd, A);
721 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000722
723 // Remaining cases assume at least that B and D are constant, and depend on
724 // their actual values. This isn't strictly, necessary, just a "handle the
725 // easy cases for now" decision.
726 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
727 if (BCst == 0) return 0;
728 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
729 if (DCst == 0) return 0;
730
731 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
732 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
733 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
734 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
735 // Only valid if one of the masks is a superset of the other (check "B&D" is
736 // the same as either B or D).
737 APInt NewMask = BCst->getValue() & DCst->getValue();
738
739 if (NewMask == BCst->getValue())
740 return LHS;
741 else if (NewMask == DCst->getValue())
742 return RHS;
743 }
744 if (mask & FoldMskICmp_AMask_NotAllOnes) {
745 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
746 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
747 // Only valid if one of the masks is a superset of the other (check "B|D" is
748 // the same as either B or D).
749 APInt NewMask = BCst->getValue() | DCst->getValue();
750
751 if (NewMask == BCst->getValue())
752 return LHS;
753 else if (NewMask == DCst->getValue())
754 return RHS;
755 }
Craig Topperae48cb22012-12-20 07:15:54 +0000756 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000757 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000758 // We already know that B & C == C && D & E == E.
759 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
760 // C and E, which are shared by both the mask B and the mask D, don't
761 // contradict, then we can transform to
762 // -> (icmp eq (A & (B|D)), (C|E))
763 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000764 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000765 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000766 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000767 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
768 if (CCst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000769 if (LHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000770 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
771 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
772 if (ECst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000773 if (RHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000774 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
775 ConstantInt* MCst = dyn_cast<ConstantInt>(
776 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
777 ConstantExpr::getXor(CCst, ECst)) );
778 // if there is a conflict we should actually return a false for the
779 // whole construct
780 if (!MCst->isZero())
781 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000782 Value *newOr1 = Builder->CreateOr(B, D);
783 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
784 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000785 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
786 }
787 return 0;
788}
789
Chris Lattner0a8191e2010-01-05 07:50:36 +0000790/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000791Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000792 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
793
794 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
795 if (PredicatesFoldable(LHSCC, RHSCC)) {
796 if (LHS->getOperand(0) == RHS->getOperand(1) &&
797 LHS->getOperand(1) == RHS->getOperand(0))
798 LHS->swapOperands();
799 if (LHS->getOperand(0) == RHS->getOperand(0) &&
800 LHS->getOperand(1) == RHS->getOperand(1)) {
801 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
802 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
803 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000804 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000805 }
806 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000807
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000808 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000809 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000810 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000811
Chris Lattner0a8191e2010-01-05 07:50:36 +0000812 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
813 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
814 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
815 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
816 if (LHSCst == 0 || RHSCst == 0) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000817
Chris Lattner0a8191e2010-01-05 07:50:36 +0000818 if (LHSCst == RHSCst && LHSCC == RHSCC) {
819 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
820 // where C is a power of 2
821 if (LHSCC == ICmpInst::ICMP_ULT &&
822 LHSCst->getValue().isPowerOf2()) {
823 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000824 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000825 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000826
Chris Lattner0a8191e2010-01-05 07:50:36 +0000827 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
828 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
829 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000830 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 }
832 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000833
Benjamin Kramer101720f2011-04-28 20:09:57 +0000834 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000835 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000836 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000837 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000838 LHS->hasOneUse() && RHS->hasOneUse()) {
839 Value *V;
840 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
841
842 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000843 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000844 if (match(Val2, m_Trunc(m_Value(V))) &&
845 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
846 SmallCst = RHSCst;
847 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000848 } else if (match(Val, m_Trunc(m_Value(V))) &&
849 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000850 SmallCst = LHSCst;
851 BigCst = RHSCst;
852 }
853
854 if (SmallCst && BigCst) {
855 unsigned BigBitSize = BigCst->getType()->getBitWidth();
856 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
857
858 // Check that the low bits are zero.
859 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000860 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000861 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
862 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
863 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
864 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
865 }
866 }
867 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000868
Chris Lattner0a8191e2010-01-05 07:50:36 +0000869 // From here on, we only handle:
870 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
871 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000872
Chris Lattner0a8191e2010-01-05 07:50:36 +0000873 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
874 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
875 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
876 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
877 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
878 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000879
880 // Make a constant range that's the intersection of the two icmp ranges.
881 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000882 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000883 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000884 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000885 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
886
887 if (LHSRange.intersectWith(RHSRange).isEmptySet())
888 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
889
Chris Lattner0a8191e2010-01-05 07:50:36 +0000890 // We can't fold (ugt x, C) & (sgt x, C2).
891 if (!PredicatesFoldable(LHSCC, RHSCC))
892 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000893
Chris Lattner0a8191e2010-01-05 07:50:36 +0000894 // Ensure that the larger constant is on the RHS.
895 bool ShouldSwap;
896 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000897 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000898 CmpInst::isSigned(RHSCC)))
899 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
900 else
901 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000902
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 if (ShouldSwap) {
904 std::swap(LHS, RHS);
905 std::swap(LHSCst, RHSCst);
906 std::swap(LHSCC, RHSCC);
907 }
908
Dan Gohman4a618822010-02-10 16:03:48 +0000909 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000910 // comparing a value against two constants and and'ing the result
911 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000912 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
913 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000914 // are not equal and that the larger constant is on the RHS
915 assert(LHSCst != RHSCst && "Compares not folded above?");
916
917 switch (LHSCC) {
918 default: llvm_unreachable("Unknown integer condition code!");
919 case ICmpInst::ICMP_EQ:
920 switch (RHSCC) {
921 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000922 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
923 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
924 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000925 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000926 }
927 case ICmpInst::ICMP_NE:
928 switch (RHSCC) {
929 default: llvm_unreachable("Unknown integer condition code!");
930 case ICmpInst::ICMP_ULT:
931 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000932 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000933 break; // (X != 13 & X u< 15) -> no change
934 case ICmpInst::ICMP_SLT:
935 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000936 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000937 break; // (X != 13 & X s< 15) -> no change
938 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
939 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
940 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000941 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000942 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000943 // Special case to get the ordering right when the values wrap around
944 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +0000945 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000946 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000947 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
948 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
949 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000950 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
951 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 }
953 break; // (X != 13 & X != 15) -> no change
954 }
955 break;
956 case ICmpInst::ICMP_ULT:
957 switch (RHSCC) {
958 default: llvm_unreachable("Unknown integer condition code!");
959 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
960 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000961 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000962 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
963 break;
964 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
965 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000966 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
968 break;
969 }
970 break;
971 case ICmpInst::ICMP_SLT:
972 switch (RHSCC) {
973 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000974 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
975 break;
976 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
977 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000978 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000979 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
980 break;
981 }
982 break;
983 case ICmpInst::ICMP_UGT:
984 switch (RHSCC) {
985 default: llvm_unreachable("Unknown integer condition code!");
986 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
987 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000988 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000989 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
990 break;
991 case ICmpInst::ICMP_NE:
992 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000993 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000994 break; // (X u> 13 & X != 15) -> no change
995 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000996 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000997 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
998 break;
999 }
1000 break;
1001 case ICmpInst::ICMP_SGT:
1002 switch (RHSCC) {
1003 default: llvm_unreachable("Unknown integer condition code!");
1004 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1005 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001006 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001007 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1008 break;
1009 case ICmpInst::ICMP_NE:
1010 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001011 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 break; // (X s> 13 & X != 15) -> no change
1013 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001014 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001015 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1016 break;
1017 }
1018 break;
1019 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001020
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 return 0;
1022}
1023
Chris Lattner067459c2010-03-05 08:46:26 +00001024/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1025/// instcombine, this returns a Value which should already be inserted into the
1026/// function.
1027Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1029 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001030 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1031 return 0;
1032
Chris Lattner0a8191e2010-01-05 07:50:36 +00001033 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1034 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1035 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1036 // If either of the constants are nans, then the whole thing returns
1037 // false.
1038 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001039 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001040 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001042
Chris Lattner0a8191e2010-01-05 07:50:36 +00001043 // Handle vector zeros. This occurs because the canonical form of
1044 // "fcmp ord x,x" is "fcmp ord x, 0".
1045 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1046 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001047 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001048 return 0;
1049 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001050
Chris Lattner0a8191e2010-01-05 07:50:36 +00001051 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1052 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1053 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001054
1055
Chris Lattner0a8191e2010-01-05 07:50:36 +00001056 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1057 // Swap RHS operands to match LHS.
1058 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1059 std::swap(Op1LHS, Op1RHS);
1060 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001061
Chris Lattner0a8191e2010-01-05 07:50:36 +00001062 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1063 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1064 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001065 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001066 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001067 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001068 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001069 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001070 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001071 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001072
Chris Lattner0a8191e2010-01-05 07:50:36 +00001073 bool Op0Ordered;
1074 bool Op1Ordered;
1075 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1076 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001077 // uno && ord -> false
1078 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1079 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001080 if (Op1Pred == 0) {
1081 std::swap(LHS, RHS);
1082 std::swap(Op0Pred, Op1Pred);
1083 std::swap(Op0Ordered, Op1Ordered);
1084 }
1085 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001086 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001087 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001088 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1089 return LHS;
1090 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001091 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001092
Chris Lattner0a8191e2010-01-05 07:50:36 +00001093 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001094 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001095 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001096 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001097 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001098 }
1099 }
1100
1101 return 0;
1102}
1103
1104
1105Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001106 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1108
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001109 if (Value *V = SimplifyAndInst(Op0, Op1, DL))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001110 return ReplaceInstUsesWith(I, V);
1111
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001112 // (A|B)&(A|C) -> A|(B&C) etc
1113 if (Value *V = SimplifyUsingDistributiveLaws(I))
1114 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001115
Craig Topper9d4171a2012-12-20 07:09:41 +00001116 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117 // purpose is to compute bits we don't care about.
1118 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001119 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001120
1121 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1122 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001123
1124 // Optimize a variety of ((val OP C1) & C2) combinations...
1125 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1126 Value *Op0LHS = Op0I->getOperand(0);
1127 Value *Op0RHS = Op0I->getOperand(1);
1128 switch (Op0I->getOpcode()) {
1129 default: break;
1130 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001131 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001132 // If the mask is only needed on one incoming arm, push it up.
1133 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001134
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001135 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001136 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1137 // Not masking anything out for the LHS, move to RHS.
1138 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1139 Op0RHS->getName()+".masked");
1140 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1141 }
1142 if (!isa<Constant>(Op0RHS) &&
1143 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1144 // Not masking anything out for the RHS, move to LHS.
1145 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1146 Op0LHS->getName()+".masked");
1147 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1148 }
1149
1150 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001151 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001152 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001153 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1154 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1155 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001156 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1157 return BinaryOperator::CreateAnd(V, AndRHS);
1158 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1159 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1160 break;
1161
1162 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001163 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1164 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1165 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001166 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1167 return BinaryOperator::CreateAnd(V, AndRHS);
1168
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001169 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001170 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001171 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001172 uint32_t BitWidth = AndRHSMask.getBitWidth();
1173 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1174 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1175
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001176 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001177 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1178 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1179 }
1180 }
1181 break;
1182
1183 case Instruction::Shl:
1184 case Instruction::LShr:
1185 // (1 << x) & 1 --> zext(x == 0)
1186 // (1 >> x) & 1 --> zext(x == 0)
1187 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1188 Value *NewICmp =
1189 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1190 return new ZExtInst(NewICmp, I.getType());
1191 }
1192 break;
1193 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001194
Chris Lattner0a8191e2010-01-05 07:50:36 +00001195 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1196 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1197 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001198 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001199
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001200 // If this is an integer truncation, and if the source is an 'and' with
1201 // immediate, transform it. This frequently occurs for bitfield accesses.
1202 {
1203 Value *X = 0; ConstantInt *YC = 0;
1204 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1205 // Change: and (trunc (and X, YC) to T), C2
1206 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001207 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001208 // other simplifications.
1209 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1210 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1211 C3 = ConstantExpr::getAnd(C3, AndRHS);
1212 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001213 }
1214 }
1215
1216 // Try to fold constant and into select arguments.
1217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1218 if (Instruction *R = FoldOpIntoSelect(I, SI))
1219 return R;
1220 if (isa<PHINode>(Op0))
1221 if (Instruction *NV = FoldOpIntoPhi(I))
1222 return NV;
1223 }
1224
1225
1226 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1227 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1228 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1229 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1230 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1231 I.getName()+".demorgan");
1232 return BinaryOperator::CreateNot(Or);
1233 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001234
Chris Lattner0a8191e2010-01-05 07:50:36 +00001235 {
1236 Value *A = 0, *B = 0, *C = 0, *D = 0;
1237 // (A|B) & ~(A&B) -> A^B
1238 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1239 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1240 ((A == C && B == D) || (A == D && B == C)))
1241 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001242
Chris Lattner0a8191e2010-01-05 07:50:36 +00001243 // ~(A&B) & (A|B) -> A^B
1244 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1245 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1246 ((A == C && B == D) || (A == D && B == C)))
1247 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001248
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001249 // A&(A^B) => A & ~B
1250 {
1251 Value *tmpOp0 = Op0;
1252 Value *tmpOp1 = Op1;
1253 if (Op0->hasOneUse() &&
1254 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1255 if (A == Op1 || B == Op1 ) {
1256 tmpOp1 = Op0;
1257 tmpOp0 = Op1;
1258 // Simplify below
1259 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001260 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001261
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001262 if (tmpOp1->hasOneUse() &&
1263 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1264 if (B == tmpOp0) {
1265 std::swap(A, B);
1266 }
1267 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1268 // A is originally -1 (or a vector of -1 and undefs), then we enter
1269 // an endless loop. By checking that A is non-constant we ensure that
1270 // we will never get to the loop.
1271 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001272 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001274 }
1275
1276 // (A&((~A)|B)) -> A&B
1277 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1278 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1279 return BinaryOperator::CreateAnd(A, Op1);
1280 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1281 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1282 return BinaryOperator::CreateAnd(A, Op0);
1283 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001284
Chris Lattner0a8191e2010-01-05 07:50:36 +00001285 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1286 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001287 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1288 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001289
Chris Lattner4e8137d2010-02-11 06:26:33 +00001290 // If and'ing two fcmp, try combine them into one.
1291 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1292 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001293 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1294 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001295
1296
Chris Lattner0a8191e2010-01-05 07:50:36 +00001297 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1298 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001299 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001300 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001301 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1302 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001303 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001304 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001305
Chris Lattner4e8137d2010-02-11 06:26:33 +00001306 // Only do this if the casts both really cause code to be generated.
1307 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1308 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1309 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1311 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001312
Chris Lattner4e8137d2010-02-11 06:26:33 +00001313 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1314 // cast is otherwise not optimizable. This happens for vector sexts.
1315 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1316 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001317 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001318 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001319
Chris Lattner4e8137d2010-02-11 06:26:33 +00001320 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1321 // cast is otherwise not optimizable. This happens for vector sexts.
1322 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1323 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001324 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001325 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001326 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001327 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001328
Chris Lattner0a8191e2010-01-05 07:50:36 +00001329 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1330 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1331 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001332 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 SI0->getOperand(1) == SI1->getOperand(1) &&
1334 (SI0->hasOneUse() || SI1->hasOneUse())) {
1335 Value *NewOp =
1336 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1337 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001338 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001339 SI1->getOperand(1));
1340 }
1341 }
1342
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001343 {
1344 Value *X = 0;
1345 bool OpsSwapped = false;
1346 // Canonicalize SExt or Not to the LHS
1347 if (match(Op1, m_SExt(m_Value())) ||
1348 match(Op1, m_Not(m_Value()))) {
1349 std::swap(Op0, Op1);
1350 OpsSwapped = true;
1351 }
1352
1353 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1354 if (match(Op0, m_SExt(m_Value(X))) &&
1355 X->getType()->getScalarType()->isIntegerTy(1)) {
1356 Value *Zero = Constant::getNullValue(Op1->getType());
1357 return SelectInst::Create(X, Op1, Zero);
1358 }
1359
1360 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1361 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1362 X->getType()->getScalarType()->isIntegerTy(1)) {
1363 Value *Zero = Constant::getNullValue(Op0->getType());
1364 return SelectInst::Create(X, Zero, Op1);
1365 }
1366
1367 if (OpsSwapped)
1368 std::swap(Op0, Op1);
1369 }
1370
Chris Lattner0a8191e2010-01-05 07:50:36 +00001371 return Changed ? &I : 0;
1372}
1373
1374/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1375/// capable of providing pieces of a bswap. The subexpression provides pieces
1376/// of a bswap if it is proven that each of the non-zero bytes in the output of
1377/// the expression came from the corresponding "byte swapped" byte in some other
1378/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1379/// we know that the expression deposits the low byte of %X into the high byte
1380/// of the bswap result and that all other bytes are zero. This expression is
1381/// accepted, the high byte of ByteValues is set to X to indicate a correct
1382/// match.
1383///
1384/// This function returns true if the match was unsuccessful and false if so.
1385/// On entry to the function the "OverallLeftShift" is a signed integer value
1386/// indicating the number of bytes that the subexpression is later shifted. For
1387/// example, if the expression is later right shifted by 16 bits, the
1388/// OverallLeftShift value would be -2 on entry. This is used to specify which
1389/// byte of ByteValues is actually being set.
1390///
1391/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1392/// byte is masked to zero by a user. For example, in (X & 255), X will be
1393/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1394/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1395/// always in the local (OverallLeftShift) coordinate space.
1396///
1397static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
Craig Topperb94011f2013-07-14 04:42:23 +00001398 SmallVectorImpl<Value *> &ByteValues) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001399 if (Instruction *I = dyn_cast<Instruction>(V)) {
1400 // If this is an or instruction, it may be an inner node of the bswap.
1401 if (I->getOpcode() == Instruction::Or) {
1402 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1403 ByteValues) ||
1404 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1405 ByteValues);
1406 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001407
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 // If this is a logical shift by a constant multiple of 8, recurse with
1409 // OverallLeftShift and ByteMask adjusted.
1410 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001411 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001412 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1413 // Ensure the shift amount is defined and of a byte value.
1414 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1415 return true;
1416
1417 unsigned ByteShift = ShAmt >> 3;
1418 if (I->getOpcode() == Instruction::Shl) {
1419 // X << 2 -> collect(X, +2)
1420 OverallLeftShift += ByteShift;
1421 ByteMask >>= ByteShift;
1422 } else {
1423 // X >>u 2 -> collect(X, -2)
1424 OverallLeftShift -= ByteShift;
1425 ByteMask <<= ByteShift;
1426 ByteMask &= (~0U >> (32-ByteValues.size()));
1427 }
1428
1429 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1430 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1431
Craig Topper9d4171a2012-12-20 07:09:41 +00001432 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001433 ByteValues);
1434 }
1435
1436 // If this is a logical 'and' with a mask that clears bytes, clear the
1437 // corresponding bytes in ByteMask.
1438 if (I->getOpcode() == Instruction::And &&
1439 isa<ConstantInt>(I->getOperand(1))) {
1440 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1441 unsigned NumBytes = ByteValues.size();
1442 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1443 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001444
Chris Lattner0a8191e2010-01-05 07:50:36 +00001445 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1446 // If this byte is masked out by a later operation, we don't care what
1447 // the and mask is.
1448 if ((ByteMask & (1 << i)) == 0)
1449 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001450
Chris Lattner0a8191e2010-01-05 07:50:36 +00001451 // If the AndMask is all zeros for this byte, clear the bit.
1452 APInt MaskB = AndMask & Byte;
1453 if (MaskB == 0) {
1454 ByteMask &= ~(1U << i);
1455 continue;
1456 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001457
Chris Lattner0a8191e2010-01-05 07:50:36 +00001458 // If the AndMask is not all ones for this byte, it's not a bytezap.
1459 if (MaskB != Byte)
1460 return true;
1461
1462 // Otherwise, this byte is kept.
1463 }
1464
Craig Topper9d4171a2012-12-20 07:09:41 +00001465 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001466 ByteValues);
1467 }
1468 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001469
Chris Lattner0a8191e2010-01-05 07:50:36 +00001470 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1471 // the input value to the bswap. Some observations: 1) if more than one byte
1472 // is demanded from this input, then it could not be successfully assembled
1473 // into a byteswap. At least one of the two bytes would not be aligned with
1474 // their ultimate destination.
1475 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001476 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001477
Chris Lattner0a8191e2010-01-05 07:50:36 +00001478 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1479 // is demanded, it needs to go into byte 0 of the result. This means that the
1480 // byte needs to be shifted until it lands in the right byte bucket. The
1481 // shift amount depends on the position: if the byte is coming from the high
1482 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1483 // low part, it must be shifted left.
1484 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001485 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1486 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001487
Chris Lattner0a8191e2010-01-05 07:50:36 +00001488 // If the destination byte value is already defined, the values are or'd
1489 // together, which isn't a bswap (unless it's an or of the same bits).
1490 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1491 return true;
1492 ByteValues[DestByteNo] = V;
1493 return false;
1494}
1495
1496/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1497/// If so, insert the new bswap intrinsic and return it.
1498Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001499 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001500 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001501 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001502 ITy->getBitWidth() > 32*8)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001503 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001504
Chris Lattner0a8191e2010-01-05 07:50:36 +00001505 /// ByteValues - For each byte of the result, we keep track of which value
1506 /// defines each byte.
1507 SmallVector<Value*, 8> ByteValues;
1508 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001509
Chris Lattner0a8191e2010-01-05 07:50:36 +00001510 // Try to find all the pieces corresponding to the bswap.
1511 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1512 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1513 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001514
Chris Lattner0a8191e2010-01-05 07:50:36 +00001515 // Check to see if all of the bytes come from the same value.
1516 Value *V = ByteValues[0];
1517 if (V == 0) return 0; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001518
Chris Lattner0a8191e2010-01-05 07:50:36 +00001519 // Check to make sure that all of the bytes come from the same value.
1520 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1521 if (ByteValues[i] != V)
1522 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001523 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001524 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001525 return CallInst::Create(F, V);
1526}
1527
1528/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1529/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1530/// we can simplify this expression to "cond ? C : D or B".
1531static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1532 Value *C, Value *D) {
1533 // If A is not a select of -1/0, this cannot match.
1534 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001535 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001536 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001537 return 0;
1538
1539 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001540 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001541 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001542 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001543 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001544
Chris Lattner0a8191e2010-01-05 07:50:36 +00001545 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001546 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001547 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001548 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001549 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001550 return 0;
1551}
1552
Chris Lattner067459c2010-03-05 08:46:26 +00001553/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1554Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001555 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1556
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001557 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1558 // if K1 and K2 are a one-bit mask.
1559 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1560 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1561
1562 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1563 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1564
1565 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1566 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1567 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1568 LAnd->getOpcode() == Instruction::And &&
1569 RAnd->getOpcode() == Instruction::And) {
1570
1571 Value *Mask = 0;
1572 Value *Masked = 0;
1573 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001574 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1575 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001576 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1577 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1578 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Benjamin Kramer7a74bd42014-01-19 16:48:41 +00001579 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1580 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001581 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1582 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1583 }
1584
1585 if (Masked)
1586 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1587 }
1588 }
1589
Chris Lattner0a8191e2010-01-05 07:50:36 +00001590 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1591 if (PredicatesFoldable(LHSCC, RHSCC)) {
1592 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1593 LHS->getOperand(1) == RHS->getOperand(0))
1594 LHS->swapOperands();
1595 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1596 LHS->getOperand(1) == RHS->getOperand(1)) {
1597 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1598 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1599 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001600 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001601 }
1602 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001603
1604 // handle (roughly):
1605 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001606 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001607 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001608
Chris Lattner0a8191e2010-01-05 07:50:36 +00001609 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001610 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1611 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1612 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1613 Value *A = 0, *B = 0;
1614 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1615 B = Val;
1616 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1617 A = Val2;
1618 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1619 A = RHS->getOperand(1);
1620 }
1621 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1622 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1623 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1624 B = Val2;
1625 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1626 A = Val;
1627 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1628 A = LHS->getOperand(1);
1629 }
1630 if (A && B)
1631 return Builder->CreateICmp(
1632 ICmpInst::ICMP_UGE,
1633 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1634 }
1635
1636 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner0a8191e2010-01-05 07:50:36 +00001637 if (LHSCst == 0 || RHSCst == 0) return 0;
1638
Owen Anderson8f306a72010-08-02 09:32:13 +00001639 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1640 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1641 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1642 Value *NewOr = Builder->CreateOr(Val, Val2);
1643 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1644 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001645 }
1646
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001647 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001648 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001649 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001650 ConstantInt *AddCst;
1651 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1652 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001653 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001654 }
1655
Chris Lattner0a8191e2010-01-05 07:50:36 +00001656 // From here on, we only handle:
1657 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1658 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001659
Chris Lattner0a8191e2010-01-05 07:50:36 +00001660 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1661 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1662 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1663 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1664 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1665 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001666
Chris Lattner0a8191e2010-01-05 07:50:36 +00001667 // We can't fold (ugt x, C) | (sgt x, C2).
1668 if (!PredicatesFoldable(LHSCC, RHSCC))
1669 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001670
Chris Lattner0a8191e2010-01-05 07:50:36 +00001671 // Ensure that the larger constant is on the RHS.
1672 bool ShouldSwap;
1673 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001674 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675 CmpInst::isSigned(RHSCC)))
1676 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1677 else
1678 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001679
Chris Lattner0a8191e2010-01-05 07:50:36 +00001680 if (ShouldSwap) {
1681 std::swap(LHS, RHS);
1682 std::swap(LHSCst, RHSCst);
1683 std::swap(LHSCC, RHSCC);
1684 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001685
Dan Gohman4a618822010-02-10 16:03:48 +00001686 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001687 // comparing a value against two constants and or'ing the result
1688 // together. Because of the above check, we know that we only have
1689 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1690 // icmp folding check above), that the two constants are not
1691 // equal.
1692 assert(LHSCst != RHSCst && "Compares not folded above?");
1693
1694 switch (LHSCC) {
1695 default: llvm_unreachable("Unknown integer condition code!");
1696 case ICmpInst::ICMP_EQ:
1697 switch (RHSCC) {
1698 default: llvm_unreachable("Unknown integer condition code!");
1699 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001700 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001701 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001702 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001703 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1704
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001705 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1706 if (Xor.isPowerOf2()) {
1707 Value *NegCst = Builder->getInt(~Xor);
1708 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1709 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1710 }
1711 }
1712
David Majnemer1fae1952013-04-14 21:15:43 +00001713 if (LHSCst == SubOne(RHSCst)) {
1714 // (X == 13 | X == 14) -> X-13 <u 2
1715 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1716 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1717 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1718 return Builder->CreateICmpULT(Add, AddCST);
1719 }
1720
Chris Lattner0a8191e2010-01-05 07:50:36 +00001721 break; // (X == 13 | X == 15) -> no change
1722 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1723 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1724 break;
1725 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1726 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1727 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001728 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001729 }
1730 break;
1731 case ICmpInst::ICMP_NE:
1732 switch (RHSCC) {
1733 default: llvm_unreachable("Unknown integer condition code!");
1734 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1735 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1736 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001737 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001738 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1739 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1740 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001741 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001742 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001743 case ICmpInst::ICMP_ULT:
1744 switch (RHSCC) {
1745 default: llvm_unreachable("Unknown integer condition code!");
1746 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1747 break;
1748 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1749 // If RHSCst is [us]MAXINT, it is always false. Not handling
1750 // this can cause overflow.
1751 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001752 return LHS;
1753 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001754 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1755 break;
1756 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1757 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001758 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001759 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1760 break;
1761 }
1762 break;
1763 case ICmpInst::ICMP_SLT:
1764 switch (RHSCC) {
1765 default: llvm_unreachable("Unknown integer condition code!");
1766 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1767 break;
1768 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1769 // If RHSCst is [us]MAXINT, it is always false. Not handling
1770 // this can cause overflow.
1771 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001772 return LHS;
1773 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001774 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1775 break;
1776 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1777 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001778 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001779 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1780 break;
1781 }
1782 break;
1783 case ICmpInst::ICMP_UGT:
1784 switch (RHSCC) {
1785 default: llvm_unreachable("Unknown integer condition code!");
1786 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1787 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001788 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001789 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1790 break;
1791 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1792 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001793 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1795 break;
1796 }
1797 break;
1798 case ICmpInst::ICMP_SGT:
1799 switch (RHSCC) {
1800 default: llvm_unreachable("Unknown integer condition code!");
1801 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1802 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001803 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1805 break;
1806 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1807 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001808 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1810 break;
1811 }
1812 break;
1813 }
1814 return 0;
1815}
1816
Chris Lattner067459c2010-03-05 08:46:26 +00001817/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1818/// instcombine, this returns a Value which should already be inserted into the
1819/// function.
1820Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001822 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1824 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1825 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1826 // If either of the constants are nans, then the whole thing returns
1827 // true.
1828 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001829 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001830
Chris Lattner0a8191e2010-01-05 07:50:36 +00001831 // Otherwise, no need to compare the two constants, compare the
1832 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001833 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001835
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836 // Handle vector zeros. This occurs because the canonical form of
1837 // "fcmp uno x,x" is "fcmp uno x, 0".
1838 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1839 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001840 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001841
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842 return 0;
1843 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001844
Chris Lattner0a8191e2010-01-05 07:50:36 +00001845 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1846 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1847 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001848
Chris Lattner0a8191e2010-01-05 07:50:36 +00001849 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1850 // Swap RHS operands to match LHS.
1851 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1852 std::swap(Op1LHS, Op1RHS);
1853 }
1854 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1855 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1856 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001857 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001858 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001859 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001860 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001861 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001862 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001863 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001864 bool Op0Ordered;
1865 bool Op1Ordered;
1866 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1867 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1868 if (Op0Ordered == Op1Ordered) {
1869 // If both are ordered or unordered, return a new fcmp with
1870 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001871 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001872 }
1873 }
1874 return 0;
1875}
1876
1877/// FoldOrWithConstants - This helper function folds:
1878///
1879/// ((A | B) & C1) | (B & C2)
1880///
1881/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001882///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883/// (A & C1) | B
1884///
1885/// when the XOR of the two constants is "all ones" (-1).
1886Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1887 Value *A, Value *B, Value *C) {
1888 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1889 if (!CI1) return 0;
1890
1891 Value *V1 = 0;
1892 ConstantInt *CI2 = 0;
1893 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1894
1895 APInt Xor = CI1->getValue() ^ CI2->getValue();
1896 if (!Xor.isAllOnesValue()) return 0;
1897
1898 if (V1 == A || V1 == B) {
1899 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1900 return BinaryOperator::CreateOr(NewOp, V1);
1901 }
1902
1903 return 0;
1904}
1905
1906Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001907 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1909
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001910 if (Value *V = SimplifyOrInst(Op0, Op1, DL))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001911 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001912
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001913 // (A&B)|(A&C) -> A&(B|C) etc
1914 if (Value *V = SimplifyUsingDistributiveLaws(I))
1915 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001916
Craig Topper9d4171a2012-12-20 07:09:41 +00001917 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001918 // purpose is to compute bits we don't care about.
1919 if (SimplifyDemandedInstructionBits(I))
1920 return &I;
1921
1922 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1923 ConstantInt *C1 = 0; Value *X = 0;
1924 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001925 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001927 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001928 Op0->hasOneUse()) {
1929 Value *Or = Builder->CreateOr(X, RHS);
1930 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001931 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001932 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001933 }
1934
1935 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1936 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1937 Op0->hasOneUse()) {
1938 Value *Or = Builder->CreateOr(X, RHS);
1939 Or->takeName(Op0);
1940 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001941 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001942 }
1943
1944 // Try to fold constant and into select arguments.
1945 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1946 if (Instruction *R = FoldOpIntoSelect(I, SI))
1947 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001948
Chris Lattner0a8191e2010-01-05 07:50:36 +00001949 if (isa<PHINode>(Op0))
1950 if (Instruction *NV = FoldOpIntoPhi(I))
1951 return NV;
1952 }
1953
1954 Value *A = 0, *B = 0;
1955 ConstantInt *C1 = 0, *C2 = 0;
1956
1957 // (A | B) | C and A | (B | C) -> bswap if possible.
1958 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1959 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1960 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001961 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1962 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001963 if (Instruction *BSwap = MatchBSwap(I))
1964 return BSwap;
1965 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001966
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001967 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968 if (Op0->hasOneUse() &&
1969 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1970 MaskedValueIsZero(Op1, C1->getValue())) {
1971 Value *NOr = Builder->CreateOr(A, Op1);
1972 NOr->takeName(Op0);
1973 return BinaryOperator::CreateXor(NOr, C1);
1974 }
1975
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001976 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 if (Op1->hasOneUse() &&
1978 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1979 MaskedValueIsZero(Op0, C1->getValue())) {
1980 Value *NOr = Builder->CreateOr(A, Op0);
1981 NOr->takeName(Op0);
1982 return BinaryOperator::CreateXor(NOr, C1);
1983 }
1984
1985 // (A & C)|(B & D)
1986 Value *C = 0, *D = 0;
1987 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1988 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001989 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001990 C1 = dyn_cast<ConstantInt>(C);
1991 C2 = dyn_cast<ConstantInt>(D);
1992 if (C1 && C2) { // (A & C1)|(B & C2)
1993 // If we have: ((V + N) & C1) | (V & C2)
1994 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1995 // replace with V+N.
1996 if (C1->getValue() == ~C2->getValue()) {
1997 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1998 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1999 // Add commutes, try both ways.
2000 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2001 return ReplaceInstUsesWith(I, A);
2002 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2003 return ReplaceInstUsesWith(I, A);
2004 }
2005 // Or commutes, try both ways.
2006 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
2007 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2008 // Add commutes, try both ways.
2009 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2010 return ReplaceInstUsesWith(I, B);
2011 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2012 return ReplaceInstUsesWith(I, B);
2013 }
2014 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002015
Chris Lattner0a8191e2010-01-05 07:50:36 +00002016 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002017 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002018 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002019 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2020 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2021 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2022 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002023 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002024 // Or commutes, try both ways.
2025 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2026 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2027 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2028 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002029 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002030
Chris Lattner95188692010-01-11 06:55:24 +00002031 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002032 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Chris Lattner95188692010-01-11 06:55:24 +00002033 ConstantInt *C3 = 0, *C4 = 0;
2034 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2035 (C3->getValue() & ~C1->getValue()) == 0 &&
2036 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2037 (C4->getValue() & ~C2->getValue()) == 0) {
2038 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2039 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002040 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002041 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002042 }
2043 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002044
Chris Lattner8e2c4712010-02-02 02:43:51 +00002045 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2046 // Don't do this for vector select idioms, the code generator doesn't handle
2047 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002048 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002049 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2050 return Match;
2051 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2052 return Match;
2053 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2054 return Match;
2055 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2056 return Match;
2057 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002058
2059 // ((A&~B)|(~A&B)) -> A^B
2060 if ((match(C, m_Not(m_Specific(D))) &&
2061 match(B, m_Not(m_Specific(A)))))
2062 return BinaryOperator::CreateXor(A, D);
2063 // ((~B&A)|(~A&B)) -> A^B
2064 if ((match(A, m_Not(m_Specific(D))) &&
2065 match(B, m_Not(m_Specific(C)))))
2066 return BinaryOperator::CreateXor(C, D);
2067 // ((A&~B)|(B&~A)) -> A^B
2068 if ((match(C, m_Not(m_Specific(B))) &&
2069 match(D, m_Not(m_Specific(A)))))
2070 return BinaryOperator::CreateXor(A, B);
2071 // ((~B&A)|(B&~A)) -> A^B
2072 if ((match(A, m_Not(m_Specific(B))) &&
2073 match(D, m_Not(m_Specific(C)))))
2074 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002075
2076 // ((A|B)&1)|(B&-2) -> (A&1) | B
2077 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2078 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2079 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2080 if (Ret) return Ret;
2081 }
2082 // (B&-2)|((A|B)&1) -> (A&1) | B
2083 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2084 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2085 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2086 if (Ret) return Ret;
2087 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002088 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002089
Chris Lattner0a8191e2010-01-05 07:50:36 +00002090 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2091 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2092 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00002093 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002094 SI0->getOperand(1) == SI1->getOperand(1) &&
2095 (SI0->hasOneUse() || SI1->hasOneUse())) {
2096 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2097 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002098 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002099 SI1->getOperand(1));
2100 }
2101 }
2102
Chris Lattner0a8191e2010-01-05 07:50:36 +00002103 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2104 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2105 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2106 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2107 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2108 I.getName()+".demorgan");
2109 return BinaryOperator::CreateNot(And);
2110 }
2111
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002112 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002113 bool SwappedForXor = false;
2114 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002115 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002116 SwappedForXor = true;
2117 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002118
2119 // A | ( A ^ B) -> A | B
2120 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002121 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002122 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2123 if (Op0 == A || Op0 == B)
2124 return BinaryOperator::CreateOr(A, B);
2125
Chad Rosier7813dce2012-04-26 23:29:14 +00002126 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2127 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2128 return BinaryOperator::CreateOr(A, B);
2129
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002130 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2131 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2132 return BinaryOperator::CreateOr(Not, Op0);
2133 }
2134 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2135 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2136 return BinaryOperator::CreateOr(Not, Op0);
2137 }
2138 }
2139
2140 // A | ~(A | B) -> A | ~B
2141 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002142 if (match(Op1, m_Not(m_Value(A))))
2143 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002144 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2145 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2146 B->getOpcode() == Instruction::Xor)) {
2147 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2148 B->getOperand(0);
2149 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2150 return BinaryOperator::CreateOr(Not, Op0);
2151 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002152
Eli Friedmane06535b2012-03-16 00:52:42 +00002153 if (SwappedForXor)
2154 std::swap(Op0, Op1);
2155
Chris Lattner0a8191e2010-01-05 07:50:36 +00002156 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2157 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00002158 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2159 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002160
Chris Lattner4e8137d2010-02-11 06:26:33 +00002161 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2162 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2163 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002164 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2165 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002166
Chris Lattner0a8191e2010-01-05 07:50:36 +00002167 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2168 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002169 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2170 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002171 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002172 if (SrcTy == Op1C->getOperand(0)->getType() &&
2173 SrcTy->isIntOrIntVectorTy()) {
2174 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002175
Chris Lattner311aa632011-01-15 05:40:29 +00002176 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2177 // Only do this if the casts both really cause code to be
2178 // generated.
2179 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2180 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2181 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2182 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002183 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002184
Chris Lattner311aa632011-01-15 05:40:29 +00002185 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2186 // cast is otherwise not optimizable. This happens for vector sexts.
2187 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2188 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2189 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2190 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002191
Chris Lattner311aa632011-01-15 05:40:29 +00002192 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2193 // cast is otherwise not optimizable. This happens for vector sexts.
2194 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2195 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2196 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2197 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002198 }
Chris Lattner311aa632011-01-15 05:40:29 +00002199 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002200 }
Eli Friedman23956262011-04-14 22:41:27 +00002201
2202 // or(sext(A), B) -> A ? -1 : B where A is an i1
2203 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2204 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2205 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2206 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2207 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2208
Owen Andersonc237a842010-09-13 17:59:27 +00002209 // Note: If we've gotten to the point of visiting the outer OR, then the
2210 // inner one couldn't be simplified. If it was a constant, then it won't
2211 // be simplified by a later pass either, so we try swapping the inner/outer
2212 // ORs in the hopes that we'll be able to simplify it this way.
2213 // (X|C) | V --> (X|V) | C
2214 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2215 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2216 Value *Inner = Builder->CreateOr(A, Op1);
2217 Inner->takeName(Op0);
2218 return BinaryOperator::CreateOr(Inner, C1);
2219 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002220
Bill Wendling23242092013-02-16 23:41:36 +00002221 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2222 // Since this OR statement hasn't been optimized further yet, we hope
2223 // that this transformation will allow the new ORs to be optimized.
2224 {
2225 Value *X = 0, *Y = 0;
2226 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2227 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2228 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2229 Value *orTrue = Builder->CreateOr(A, C);
2230 Value *orFalse = Builder->CreateOr(B, D);
2231 return SelectInst::Create(X, orTrue, orFalse);
2232 }
2233 }
2234
Chris Lattner0a8191e2010-01-05 07:50:36 +00002235 return Changed ? &I : 0;
2236}
2237
2238Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002239 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002240 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2241
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002242 if (Value *V = SimplifyXorInst(Op0, Op1, DL))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002243 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002244
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002245 // (A&B)^(A&C) -> A&(B^C) etc
2246 if (Value *V = SimplifyUsingDistributiveLaws(I))
2247 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002248
Craig Topper9d4171a2012-12-20 07:09:41 +00002249 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002250 // purpose is to compute bits we don't care about.
2251 if (SimplifyDemandedInstructionBits(I))
2252 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002253
2254 // Is this a ~ operation?
2255 if (Value *NotOp = dyn_castNotVal(&I)) {
2256 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002257 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002258 Op0I->getOpcode() == Instruction::Or) {
2259 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2260 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2261 if (dyn_castNotVal(Op0I->getOperand(1)))
2262 Op0I->swapOperands();
2263 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2264 Value *NotY =
2265 Builder->CreateNot(Op0I->getOperand(1),
2266 Op0I->getOperand(1)->getName()+".not");
2267 if (Op0I->getOpcode() == Instruction::And)
2268 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2269 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2270 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002271
Chris Lattner0a8191e2010-01-05 07:50:36 +00002272 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2273 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002274 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002275 isFreeToInvert(Op0I->getOperand(1))) {
2276 Value *NotX =
2277 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2278 Value *NotY =
2279 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2280 if (Op0I->getOpcode() == Instruction::And)
2281 return BinaryOperator::CreateOr(NotX, NotY);
2282 return BinaryOperator::CreateAnd(NotX, NotY);
2283 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002284
2285 } else if (Op0I->getOpcode() == Instruction::AShr) {
2286 // ~(~X >>s Y) --> (X >>s Y)
2287 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2288 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289 }
2290 }
2291 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002292
2293
Chris Lattner0a8191e2010-01-05 07:50:36 +00002294 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002295 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002296 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002297 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2298 return CmpInst::Create(CI->getOpcode(),
2299 CI->getInversePredicate(),
2300 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002301
2302 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2303 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2304 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2305 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2306 Instruction::CastOps Opcode = Op0C->getOpcode();
2307 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002308 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002309 Op0C->getDestTy()))) {
2310 CI->setPredicate(CI->getInversePredicate());
2311 return CastInst::Create(Opcode, CI, Op0C->getType());
2312 }
2313 }
2314 }
2315 }
2316
2317 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2318 // ~(c-X) == X-c-1 == X+(-c-1)
2319 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2320 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2321 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2322 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2323 ConstantInt::get(I.getType(), 1));
2324 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2325 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002326
Chris Lattner0a8191e2010-01-05 07:50:36 +00002327 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2328 if (Op0I->getOpcode() == Instruction::Add) {
2329 // ~(X-c) --> (-c-1)-X
2330 if (RHS->isAllOnesValue()) {
2331 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2332 return BinaryOperator::CreateSub(
2333 ConstantExpr::getSub(NegOp0CI,
2334 ConstantInt::get(I.getType(), 1)),
2335 Op0I->getOperand(0));
2336 } else if (RHS->getValue().isSignBit()) {
2337 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002338 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002339 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2340
2341 }
2342 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002343 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002344 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2345 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2346 // Anything in both C1 and C2 is known to be zero, remove it from
2347 // NewRHS.
2348 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002349 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002350 ConstantExpr::getNot(CommonBits));
2351 Worklist.Add(Op0I);
2352 I.setOperand(0, Op0I->getOperand(0));
2353 I.setOperand(1, NewRHS);
2354 return &I;
2355 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002356 } else if (Op0I->getOpcode() == Instruction::LShr) {
2357 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2358 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002359 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002360 ConstantInt *C1;
2361 if (Op0I->hasOneUse() &&
2362 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2363 E1->getOpcode() == Instruction::Xor &&
2364 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2365 // fold (C1 >> C2) ^ C3
2366 ConstantInt *C2 = Op0CI, *C3 = RHS;
2367 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2368 FoldConst ^= C3->getValue();
2369 // Prepare the two operands.
2370 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2371 Opnd0->takeName(Op0I);
2372 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2373 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2374
2375 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2376 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002377 }
2378 }
2379 }
2380
2381 // Try to fold constant and into select arguments.
2382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2383 if (Instruction *R = FoldOpIntoSelect(I, SI))
2384 return R;
2385 if (isa<PHINode>(Op0))
2386 if (Instruction *NV = FoldOpIntoPhi(I))
2387 return NV;
2388 }
2389
Chris Lattner0a8191e2010-01-05 07:50:36 +00002390 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2391 if (Op1I) {
2392 Value *A, *B;
2393 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2394 if (A == Op0) { // B^(B|A) == (A|B)^B
2395 Op1I->swapOperands();
2396 I.swapOperands();
2397 std::swap(Op0, Op1);
2398 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2399 I.swapOperands(); // Simplified below.
2400 std::swap(Op0, Op1);
2401 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002402 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002403 Op1I->hasOneUse()){
2404 if (A == Op0) { // A^(A&B) -> A^(B&A)
2405 Op1I->swapOperands();
2406 std::swap(A, B);
2407 }
2408 if (B == Op0) { // A^(B&A) -> (B&A)^A
2409 I.swapOperands(); // Simplified below.
2410 std::swap(Op0, Op1);
2411 }
2412 }
2413 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002414
Chris Lattner0a8191e2010-01-05 07:50:36 +00002415 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2416 if (Op0I) {
2417 Value *A, *B;
2418 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2419 Op0I->hasOneUse()) {
2420 if (A == Op1) // (B|A)^B == (A|B)^B
2421 std::swap(A, B);
2422 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002423 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002424 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002425 Op0I->hasOneUse()){
2426 if (A == Op1) // (A&B)^A -> (B&A)^A
2427 std::swap(A, B);
2428 if (B == Op1 && // (B&A)^A == ~B & A
2429 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002430 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002431 }
2432 }
2433 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002434
Chris Lattner0a8191e2010-01-05 07:50:36 +00002435 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Craig Topper9d4171a2012-12-20 07:09:41 +00002436 if (Op0I && Op1I && Op0I->isShift() &&
2437 Op0I->getOpcode() == Op1I->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002438 Op0I->getOperand(1) == Op1I->getOperand(1) &&
Benjamin Kramer9d5849f2012-05-28 20:52:48 +00002439 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440 Value *NewOp =
2441 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2442 Op0I->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002443 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444 Op1I->getOperand(1));
2445 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002446
Chris Lattner0a8191e2010-01-05 07:50:36 +00002447 if (Op0I && Op1I) {
2448 Value *A, *B, *C, *D;
2449 // (A & B)^(A | B) -> A ^ B
2450 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2451 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002452 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453 return BinaryOperator::CreateXor(A, B);
2454 }
2455 // (A | B)^(A & B) -> A ^ B
2456 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2457 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002458 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002459 return BinaryOperator::CreateXor(A, B);
2460 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002461 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002462
Chris Lattner0a8191e2010-01-05 07:50:36 +00002463 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2464 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2465 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2466 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2467 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2468 LHS->getOperand(1) == RHS->getOperand(0))
2469 LHS->swapOperands();
2470 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2471 LHS->getOperand(1) == RHS->getOperand(1)) {
2472 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2473 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2474 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002475 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002476 getNewICmpValue(isSigned, Code, Op0, Op1,
2477 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002478 }
2479 }
2480
2481 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2482 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2483 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2484 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002485 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002486 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002487 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002488 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002489 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002490 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002491 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002492 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2493 Op1C->getOperand(0), I.getName());
2494 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2495 }
2496 }
2497 }
2498
2499 return Changed ? &I : 0;
2500}