blob: b631b2856526c5950722d7afed30662eb2372d94 [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 Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Intrinsics.h"
Anders Carlssonda80afe2011-03-01 15:05:01 +000017#include "llvm/Support/ConstantRange.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000018#include "llvm/Support/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
23
24/// AddOne - Add one to a ConstantInt.
Jakub Staszak2ef36b62013-03-09 11:18:59 +000025static Constant *AddOne(ConstantInt *C) {
26 return ConstantInt::get(C->getContext(), C->getValue() + 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +000027}
28/// SubOne - Subtract one from a ConstantInt.
29static Constant *SubOne(ConstantInt *C) {
30 return ConstantInt::get(C->getContext(), C->getValue()-1);
31}
32
33/// isFreeToInvert - Return true if the specified value is free to invert (apply
34/// ~ to). This happens in cases where the ~ can be eliminated.
35static inline bool isFreeToInvert(Value *V) {
36 // ~(~(X)) -> X.
37 if (BinaryOperator::isNot(V))
38 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000039
Chris Lattner0a8191e2010-01-05 07:50:36 +000040 // Constants can be considered to be not'ed values.
41 if (isa<ConstantInt>(V))
42 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +000043
Chris Lattner0a8191e2010-01-05 07:50:36 +000044 // Compares can be inverted if they have a single use.
45 if (CmpInst *CI = dyn_cast<CmpInst>(V))
46 return CI->hasOneUse();
Craig Topper9d4171a2012-12-20 07:09:41 +000047
Chris Lattner0a8191e2010-01-05 07:50:36 +000048 return false;
49}
50
51static inline Value *dyn_castNotVal(Value *V) {
52 // If this is not(not(x)) don't return that this is a not: we want the two
53 // not's to be folded first.
54 if (BinaryOperator::isNot(V)) {
55 Value *Operand = BinaryOperator::getNotArgument(V);
56 if (!isFreeToInvert(Operand))
57 return Operand;
58 }
Craig Topper9d4171a2012-12-20 07:09:41 +000059
Chris Lattner0a8191e2010-01-05 07:50:36 +000060 // Constants can be considered to be not'ed values...
61 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
62 return ConstantInt::get(C->getType(), ~C->getValue());
63 return 0;
64}
65
Chris Lattner0a8191e2010-01-05 07:50:36 +000066/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
67/// predicate into a three bit mask. It also returns whether it is an ordered
68/// predicate by reference.
69static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
70 isOrdered = false;
71 switch (CC) {
72 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
73 case FCmpInst::FCMP_UNO: return 0; // 000
74 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
75 case FCmpInst::FCMP_UGT: return 1; // 001
76 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
77 case FCmpInst::FCMP_UEQ: return 2; // 010
78 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
79 case FCmpInst::FCMP_UGE: return 3; // 011
80 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
81 case FCmpInst::FCMP_ULT: return 4; // 100
82 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
83 case FCmpInst::FCMP_UNE: return 5; // 101
84 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
85 case FCmpInst::FCMP_ULE: return 6; // 110
86 // True -> 7
87 default:
88 // Not expecting FCMP_FALSE and FCMP_TRUE;
89 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000090 }
91}
92
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000093/// getNewICmpValue - This is the complement of getICmpCode, which turns an
Craig Topper9d4171a2012-12-20 07:09:41 +000094/// opcode and two operands into either a constant true or false, or a brand
Chris Lattner0a8191e2010-01-05 07:50:36 +000095/// new ICmp instruction. The sign is passed in to determine which kind
96/// of predicate to use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000097static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
98 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000099 ICmpInst::Predicate NewPred;
100 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
101 return NewConstant;
102 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000103}
104
105/// getFCmpValue - This is the complement of getFCmpCode, which turns an
106/// opcode and two operands into either a FCmp instruction. isordered is passed
107/// in to determine which kind of predicate to use in the new fcmp instruction.
108static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000109 Value *LHS, Value *RHS,
110 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000111 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000112 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +0000113 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000114 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
115 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
116 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
117 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
118 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
119 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
120 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +0000121 case 7:
Owen Andersona8342002011-01-21 19:39:42 +0000122 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
123 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000124 }
Chris Lattner067459c2010-03-05 08:46:26 +0000125 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000126}
127
Chris Lattner0a8191e2010-01-05 07:50:36 +0000128// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
129// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
130// guaranteed to be a binary operator.
131Instruction *InstCombiner::OptAndOp(Instruction *Op,
132 ConstantInt *OpRHS,
133 ConstantInt *AndRHS,
134 BinaryOperator &TheAnd) {
135 Value *X = Op->getOperand(0);
136 Constant *Together = 0;
137 if (!Op->isShift())
138 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
139
140 switch (Op->getOpcode()) {
141 case Instruction::Xor:
142 if (Op->hasOneUse()) {
143 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
144 Value *And = Builder->CreateAnd(X, AndRHS);
145 And->takeName(Op);
146 return BinaryOperator::CreateXor(And, Together);
147 }
148 break;
149 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000150 if (Op->hasOneUse()){
151 if (Together != OpRHS) {
152 // (X | C1) & C2 --> (X | (C1&C2)) & C2
153 Value *Or = Builder->CreateOr(X, Together);
154 Or->takeName(Op);
155 return BinaryOperator::CreateAnd(Or, AndRHS);
156 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000157
Owen Andersonc237a842010-09-13 17:59:27 +0000158 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
159 if (TogetherCI && !TogetherCI->isZero()){
160 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
161 // NOTE: This reduces the number of bits set in the & mask, which
162 // can expose opportunities for store narrowing.
163 Together = ConstantExpr::getXor(AndRHS, Together);
164 Value *And = Builder->CreateAnd(X, Together);
165 And->takeName(Op);
166 return BinaryOperator::CreateOr(And, OpRHS);
167 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000168 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000169
Chris Lattner0a8191e2010-01-05 07:50:36 +0000170 break;
171 case Instruction::Add:
172 if (Op->hasOneUse()) {
173 // Adding a one to a single bit bit-field should be turned into an XOR
174 // of the bit. First thing to check is to see if this AND is with a
175 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000176 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000177
178 // If there is only one bit set.
179 if (AndRHSV.isPowerOf2()) {
180 // Ok, at this point, we know that we are masking the result of the
181 // ADD down to exactly one bit. If the constant we are adding has
182 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000183 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000184
185 // Check to see if any bits below the one bit set in AndRHSV are set.
186 if ((AddRHS & (AndRHSV-1)) == 0) {
187 // If not, the only thing that can effect the output of the AND is
188 // the bit specified by AndRHSV. If that bit is set, the effect of
189 // the XOR is to toggle the bit. If it is clear, then the ADD has
190 // no effect.
191 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
192 TheAnd.setOperand(0, X);
193 return &TheAnd;
194 } else {
195 // Pull the XOR out of the AND.
196 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
197 NewAnd->takeName(Op);
198 return BinaryOperator::CreateXor(NewAnd, AndRHS);
199 }
200 }
201 }
202 }
203 break;
204
205 case Instruction::Shl: {
206 // We know that the AND will not produce any of the bits shifted in, so if
207 // the anded constant includes them, clear them now!
208 //
209 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
210 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
211 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000212 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000213
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000214 if (CI->getValue() == ShlMask)
215 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000216 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000217
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000218 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000219 TheAnd.setOperand(1, CI);
220 return &TheAnd;
221 }
222 break;
223 }
224 case Instruction::LShr: {
225 // We know that the AND will not produce any of the bits shifted in, so if
226 // the anded constant includes them, clear them now! This only applies to
227 // unsigned shifts, because a signed shr may bring in set bits!
228 //
229 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
230 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
231 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000232 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000233
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000234 if (CI->getValue() == ShrMask)
235 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000236 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000237
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000238 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000239 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
240 return &TheAnd;
241 }
242 break;
243 }
244 case Instruction::AShr:
245 // Signed shr.
246 // See if this is shifting in some sign extension, then masking it out
247 // with an and.
248 if (Op->hasOneUse()) {
249 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
250 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
251 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000252 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000253 if (C == AndRHS) { // Masking out bits shifted in.
254 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
255 // Make the argument unsigned.
256 Value *ShVal = Op->getOperand(0);
257 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
258 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
259 }
260 }
261 break;
262 }
263 return 0;
264}
265
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000266/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
267/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000268/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000269/// whether to treat the V, Lo and HI as signed or not. IB is the location to
270/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000271Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
272 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000273 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000274 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
275 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000276
Chris Lattner0a8191e2010-01-05 07:50:36 +0000277 if (Inside) {
278 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000279 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000280
281 // V >= Min && V < Hi --> V < Hi
282 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000283 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000284 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000285 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000286 }
287
288 // Emit V-Lo <u Hi-Lo
289 Constant *NegLo = ConstantExpr::getNeg(Lo);
290 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
291 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000292 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000293 }
294
295 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000296 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000297
298 // V < Min || V >= Hi -> V > Hi-1
299 Hi = SubOne(cast<ConstantInt>(Hi));
300 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000301 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000302 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000303 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000304 }
305
306 // Emit V-Lo >u Hi-1-Lo
307 // Note that Hi has already had one subtracted from it, above.
308 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
309 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
310 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000311 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000312}
313
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000314// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000315// any number of 0s on either side. The 1s are allowed to wrap from LSB to
316// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
317// not, since all 1s are not contiguous.
318static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
319 const APInt& V = Val->getValue();
320 uint32_t BitWidth = Val->getType()->getBitWidth();
321 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
322
323 // look for the first zero bit after the run of ones
324 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
325 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000326 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327 return true;
328}
329
330/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
331/// where isSub determines whether the operator is a sub. If we can fold one of
332/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000333///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000334/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
335/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
336/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000337///
338/// return (A +/- B).
339///
340Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
341 ConstantInt *Mask, bool isSub,
342 Instruction &I) {
343 Instruction *LHSI = dyn_cast<Instruction>(LHS);
344 if (!LHSI || LHSI->getNumOperands() != 2 ||
345 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
346
347 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
348
349 switch (LHSI->getOpcode()) {
350 default: return 0;
351 case Instruction::And:
352 if (ConstantExpr::getAnd(N, Mask) == Mask) {
353 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000354 if ((Mask->getValue().countLeadingZeros() +
355 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000356 Mask->getValue().getBitWidth())
357 break;
358
359 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
360 // part, we don't need any explicit masks to take them out of A. If that
361 // is all N is, ignore it.
362 uint32_t MB = 0, ME = 0;
363 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
364 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
365 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
366 if (MaskedValueIsZero(RHS, Mask))
367 break;
368 }
369 }
370 return 0;
371 case Instruction::Or:
372 case Instruction::Xor:
373 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000374 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000375 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
376 && ConstantExpr::getAnd(N, Mask)->isNullValue())
377 break;
378 return 0;
379 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000380
Chris Lattner0a8191e2010-01-05 07:50:36 +0000381 if (isSub)
382 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
383 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
384}
385
Owen Anderson3fe002d2010-09-08 22:16:17 +0000386/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000387/// One of A and B is considered the mask, the other the value. This is
388/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000389/// contains only "Mask", then both A and B can be considered masks.
390/// If A is the mask, then it was proven, that (A & C) == C. This
391/// is trivial if C == A, or C == 0. If both A and C are constants, this
392/// proof is also easy.
393/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000394/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000395/// if (A & B) == A, or all bits of A are set in B.
396/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000397/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000398/// if (A & B) == 0, or all bits of A are cleared in B.
399/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000400/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000401/// contain any number of one bits and zero bits.
402/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
403/// The Part "Not" means, that in above descriptions "==" should be replaced
404/// by "!=".
405/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
406/// If the mask A contains a single bit, then the following is equivalent:
407/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
408/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
409enum MaskedICmpType {
410 FoldMskICmp_AMask_AllOnes = 1,
411 FoldMskICmp_AMask_NotAllOnes = 2,
412 FoldMskICmp_BMask_AllOnes = 4,
413 FoldMskICmp_BMask_NotAllOnes = 8,
414 FoldMskICmp_Mask_AllZeroes = 16,
415 FoldMskICmp_Mask_NotAllZeroes = 32,
416 FoldMskICmp_AMask_Mixed = 64,
417 FoldMskICmp_AMask_NotMixed = 128,
418 FoldMskICmp_BMask_Mixed = 256,
419 FoldMskICmp_BMask_NotMixed = 512
420};
421
422/// return the set of pattern classes (from MaskedICmpType)
423/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000424static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000425 ICmpInst::Predicate SCC)
426{
427 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
428 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
429 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
430 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topper9d4171a2012-12-20 07:09:41 +0000431 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000432 ACst->getValue().isPowerOf2());
Craig Topper9d4171a2012-12-20 07:09:41 +0000433 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000434 BCst->getValue().isPowerOf2());
435 unsigned result = 0;
436 if (CCst != 0 && CCst->isZero()) {
437 // if C is zero, then both A and B qualify as mask
438 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
439 FoldMskICmp_Mask_AllZeroes |
440 FoldMskICmp_AMask_Mixed |
441 FoldMskICmp_BMask_Mixed)
442 : (FoldMskICmp_Mask_NotAllZeroes |
443 FoldMskICmp_Mask_NotAllZeroes |
444 FoldMskICmp_AMask_NotMixed |
445 FoldMskICmp_BMask_NotMixed));
446 if (icmp_abit)
447 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000448 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000449 : (FoldMskICmp_AMask_AllOnes |
450 FoldMskICmp_AMask_Mixed));
451 if (icmp_bbit)
452 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000453 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454 : (FoldMskICmp_BMask_AllOnes |
455 FoldMskICmp_BMask_Mixed));
456 return result;
457 }
458 if (A == C) {
459 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
460 FoldMskICmp_AMask_Mixed)
461 : (FoldMskICmp_AMask_NotAllOnes |
462 FoldMskICmp_AMask_NotMixed));
463 if (icmp_abit)
464 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
465 FoldMskICmp_AMask_NotMixed)
466 : (FoldMskICmp_Mask_AllZeroes |
467 FoldMskICmp_AMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000468 } else if (ACst != 0 && CCst != 0 &&
469 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000470 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
471 : FoldMskICmp_AMask_NotMixed);
472 }
Craig Topperae48cb22012-12-20 07:15:54 +0000473 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000474 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
475 FoldMskICmp_BMask_Mixed)
476 : (FoldMskICmp_BMask_NotAllOnes |
477 FoldMskICmp_BMask_NotMixed));
478 if (icmp_bbit)
479 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000480 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481 : (FoldMskICmp_Mask_AllZeroes |
482 FoldMskICmp_BMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000483 } else if (BCst != 0 && CCst != 0 &&
484 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000485 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
486 : FoldMskICmp_BMask_NotMixed);
487 }
488 return result;
489}
490
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000491/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
492/// if possible. The returned predicate is either == or !=. Returns false if
493/// decomposition fails.
494static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
495 Value *&X, Value *&Y, Value *&Z) {
496 // X < 0 is equivalent to (X & SignBit) != 0.
497 if (I->getPredicate() == ICmpInst::ICMP_SLT)
498 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
499 if (C->isZero()) {
500 X = I->getOperand(0);
501 Y = ConstantInt::get(I->getContext(),
502 APInt::getSignBit(C->getBitWidth()));
503 Pred = ICmpInst::ICMP_NE;
504 Z = C;
505 return true;
506 }
507
508 // X > -1 is equivalent to (X & SignBit) == 0.
509 if (I->getPredicate() == ICmpInst::ICMP_SGT)
510 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
511 if (C->isAllOnesValue()) {
512 X = I->getOperand(0);
513 Y = ConstantInt::get(I->getContext(),
514 APInt::getSignBit(C->getBitWidth()));
515 Pred = ICmpInst::ICMP_EQ;
516 Z = ConstantInt::getNullValue(C->getType());
517 return true;
518 }
519
520 return false;
521}
522
Owen Anderson3fe002d2010-09-08 22:16:17 +0000523/// foldLogOpOfMaskedICmpsHelper:
524/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
525/// return the set of pattern classes (from MaskedICmpType)
526/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000527static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000528 Value*& B, Value*& C,
529 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000530 ICmpInst *LHS, ICmpInst *RHS,
531 ICmpInst::Predicate &LHSCC,
532 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000533 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
534 // vectors are not (yet?) supported
535 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
536
537 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000538 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000539 // and L11 & L12 == L21 & L22. The same goes for RHS.
540 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000541 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000542 // above.
543 Value *L1 = LHS->getOperand(0);
544 Value *L2 = LHS->getOperand(1);
545 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000546 // Check whether the icmp can be decomposed into a bit test.
547 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
548 L21 = L22 = L1 = 0;
549 } else {
550 // Look for ANDs in the LHS icmp.
551 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
552 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
553 L21 = L22 = 0;
554 } else {
555 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
556 return 0;
557 std::swap(L1, L2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000558 L21 = L22 = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000559 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000561
562 // Bail if LHS was a icmp that can't be decomposed into an equality.
563 if (!ICmpInst::isEquality(LHSCC))
564 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000565
566 Value *R1 = RHS->getOperand(0);
567 Value *R2 = RHS->getOperand(1);
568 Value *R11,*R12;
569 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000570 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
571 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
572 A = R11; D = R12;
573 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
574 A = R12; D = R11;
575 } else {
576 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000577 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000578 E = R2; R1 = 0; ok = true;
579 } else if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
580 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
581 A = R11; D = R12; E = R2; ok = true;
582 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000583 A = R12; D = R11; E = R2; ok = true;
584 }
585 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000586
587 // Bail if RHS was a icmp that can't be decomposed into an equality.
588 if (!ICmpInst::isEquality(RHSCC))
589 return 0;
590
591 // Look for ANDs in on the right side of the RHS icmp.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000592 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000593 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
594 A = R11; D = R12; E = R1; ok = true;
595 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000596 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000597 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000598 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000599 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000600 }
601 if (!ok)
602 return 0;
603
604 if (L11 == A) {
605 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000606 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000607 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000608 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000609 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000610 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000611 B = L21; C = L1;
612 }
613
614 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
615 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
616 return left_type & right_type;
617}
618/// foldLogOpOfMaskedICmps:
619/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
620/// into a single (icmp(A & X) ==/!= Y)
621static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
622 ICmpInst::Predicate NEWCC,
623 llvm::InstCombiner::BuilderTy* Builder) {
624 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000625 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
626 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
627 LHSCC, RHSCC);
Benjamin Kramerf7fe24f2012-01-09 17:36:29 +0000628 if (mask == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000629 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
630 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000631
632 if (NEWCC == ICmpInst::ICMP_NE)
633 mask >>= 1; // treat "Not"-states as normal states
634
635 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000636 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000637 // -> (icmp eq (A & (B|D)), 0)
638 Value* newOr = Builder->CreateOr(B, D);
639 Value* newAnd = Builder->CreateAnd(A, newOr);
640 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000641 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000642 // with B and D, having a single bit set
643 Value* zero = Constant::getNullValue(A->getType());
644 return Builder->CreateICmp(NEWCC, newAnd, zero);
645 }
Craig Topperae48cb22012-12-20 07:15:54 +0000646 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000647 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000648 // -> (icmp eq (A & (B|D)), (B|D))
649 Value* newOr = Builder->CreateOr(B, D);
650 Value* newAnd = Builder->CreateAnd(A, newOr);
651 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000652 }
Craig Topperae48cb22012-12-20 07:15:54 +0000653 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000654 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000655 // -> (icmp eq (A & (B&D)), A)
656 Value* newAnd1 = Builder->CreateAnd(B, D);
657 Value* newAnd = Builder->CreateAnd(A, newAnd1);
658 return Builder->CreateICmp(NEWCC, newAnd, A);
659 }
Craig Topperae48cb22012-12-20 07:15:54 +0000660 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000661 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000662 // We already know that B & C == C && D & E == E.
663 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
664 // C and E, which are shared by both the mask B and the mask D, don't
665 // contradict, then we can transform to
666 // -> (icmp eq (A & (B|D)), (C|E))
667 // Currently, we only handle the case of B, C, D, and E being constant.
668 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
669 if (BCst == 0) return 0;
670 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
671 if (DCst == 0) return 0;
672 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000673 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000674 // with B and D, having a single bit set
675
676 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
677 if (CCst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000678 if (LHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000679 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
680 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
681 if (ECst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000682 if (RHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000683 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
684 ConstantInt* MCst = dyn_cast<ConstantInt>(
685 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
686 ConstantExpr::getXor(CCst, ECst)) );
687 // if there is a conflict we should actually return a false for the
688 // whole construct
689 if (!MCst->isZero())
690 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000691 Value *newOr1 = Builder->CreateOr(B, D);
692 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
693 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000694 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
695 }
696 return 0;
697}
698
Chris Lattner0a8191e2010-01-05 07:50:36 +0000699/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000700Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000701 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
702
703 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
704 if (PredicatesFoldable(LHSCC, RHSCC)) {
705 if (LHS->getOperand(0) == RHS->getOperand(1) &&
706 LHS->getOperand(1) == RHS->getOperand(0))
707 LHS->swapOperands();
708 if (LHS->getOperand(0) == RHS->getOperand(0) &&
709 LHS->getOperand(1) == RHS->getOperand(1)) {
710 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
711 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
712 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000713 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000714 }
715 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000716
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000717 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
718 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
719 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000720
Chris Lattner0a8191e2010-01-05 07:50:36 +0000721 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
722 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
723 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
724 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
725 if (LHSCst == 0 || RHSCst == 0) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000726
Chris Lattner0a8191e2010-01-05 07:50:36 +0000727 if (LHSCst == RHSCst && LHSCC == RHSCC) {
728 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
729 // where C is a power of 2
730 if (LHSCC == ICmpInst::ICMP_ULT &&
731 LHSCst->getValue().isPowerOf2()) {
732 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000733 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000734 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000735
Chris Lattner0a8191e2010-01-05 07:50:36 +0000736 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
737 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
738 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000739 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000740 }
741 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000742
Benjamin Kramer101720f2011-04-28 20:09:57 +0000743 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000744 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000745 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000746 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000747 LHS->hasOneUse() && RHS->hasOneUse()) {
748 Value *V;
749 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
750
751 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000752 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000753 if (match(Val2, m_Trunc(m_Value(V))) &&
754 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
755 SmallCst = RHSCst;
756 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000757 } else if (match(Val, m_Trunc(m_Value(V))) &&
758 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000759 SmallCst = LHSCst;
760 BigCst = RHSCst;
761 }
762
763 if (SmallCst && BigCst) {
764 unsigned BigBitSize = BigCst->getType()->getBitWidth();
765 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
766
767 // Check that the low bits are zero.
768 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000769 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000770 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
771 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
772 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
773 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
774 }
775 }
776 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000777
Chris Lattner0a8191e2010-01-05 07:50:36 +0000778 // From here on, we only handle:
779 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
780 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000781
Chris Lattner0a8191e2010-01-05 07:50:36 +0000782 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
783 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
784 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
785 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
786 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
787 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000788
789 // Make a constant range that's the intersection of the two icmp ranges.
790 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000791 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000792 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000793 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000794 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
795
796 if (LHSRange.intersectWith(RHSRange).isEmptySet())
797 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
798
Chris Lattner0a8191e2010-01-05 07:50:36 +0000799 // We can't fold (ugt x, C) & (sgt x, C2).
800 if (!PredicatesFoldable(LHSCC, RHSCC))
801 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000802
Chris Lattner0a8191e2010-01-05 07:50:36 +0000803 // Ensure that the larger constant is on the RHS.
804 bool ShouldSwap;
805 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000806 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000807 CmpInst::isSigned(RHSCC)))
808 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
809 else
810 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000811
Chris Lattner0a8191e2010-01-05 07:50:36 +0000812 if (ShouldSwap) {
813 std::swap(LHS, RHS);
814 std::swap(LHSCst, RHSCst);
815 std::swap(LHSCC, RHSCC);
816 }
817
Dan Gohman4a618822010-02-10 16:03:48 +0000818 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000819 // comparing a value against two constants and and'ing the result
820 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000821 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
822 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000823 // are not equal and that the larger constant is on the RHS
824 assert(LHSCst != RHSCst && "Compares not folded above?");
825
826 switch (LHSCC) {
827 default: llvm_unreachable("Unknown integer condition code!");
828 case ICmpInst::ICMP_EQ:
829 switch (RHSCC) {
830 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
832 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
833 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000834 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000835 }
836 case ICmpInst::ICMP_NE:
837 switch (RHSCC) {
838 default: llvm_unreachable("Unknown integer condition code!");
839 case ICmpInst::ICMP_ULT:
840 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000841 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000842 break; // (X != 13 & X u< 15) -> no change
843 case ICmpInst::ICMP_SLT:
844 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000845 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000846 break; // (X != 13 & X s< 15) -> no change
847 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
848 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
849 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000850 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000851 case ICmpInst::ICMP_NE:
852 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
853 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
854 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Chris Lattner067459c2010-03-05 08:46:26 +0000855 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000856 }
857 break; // (X != 13 & X != 15) -> no change
858 }
859 break;
860 case ICmpInst::ICMP_ULT:
861 switch (RHSCC) {
862 default: llvm_unreachable("Unknown integer condition code!");
863 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
864 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000865 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000866 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
867 break;
868 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
869 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000870 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000871 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
872 break;
873 }
874 break;
875 case ICmpInst::ICMP_SLT:
876 switch (RHSCC) {
877 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000878 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
879 break;
880 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
881 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000882 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000883 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
884 break;
885 }
886 break;
887 case ICmpInst::ICMP_UGT:
888 switch (RHSCC) {
889 default: llvm_unreachable("Unknown integer condition code!");
890 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
891 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000892 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000893 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
894 break;
895 case ICmpInst::ICMP_NE:
896 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000897 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000898 break; // (X u> 13 & X != 15) -> no change
899 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000900 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000901 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
902 break;
903 }
904 break;
905 case ICmpInst::ICMP_SGT:
906 switch (RHSCC) {
907 default: llvm_unreachable("Unknown integer condition code!");
908 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
909 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000910 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
912 break;
913 case ICmpInst::ICMP_NE:
914 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000915 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000916 break; // (X s> 13 & X != 15) -> no change
917 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +0000918 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000919 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
920 break;
921 }
922 break;
923 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000924
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 return 0;
926}
927
Chris Lattner067459c2010-03-05 08:46:26 +0000928/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
929/// instcombine, this returns a Value which should already be inserted into the
930/// function.
931Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000932 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
933 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +0000934 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
935 return 0;
936
Chris Lattner0a8191e2010-01-05 07:50:36 +0000937 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
938 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
939 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
940 // If either of the constants are nans, then the whole thing returns
941 // false.
942 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000943 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +0000944 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000946
Chris Lattner0a8191e2010-01-05 07:50:36 +0000947 // Handle vector zeros. This occurs because the canonical form of
948 // "fcmp ord x,x" is "fcmp ord x, 0".
949 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
950 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000951 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 return 0;
953 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000954
Chris Lattner0a8191e2010-01-05 07:50:36 +0000955 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
956 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
957 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +0000958
959
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
961 // Swap RHS operands to match LHS.
962 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
963 std::swap(Op1LHS, Op1RHS);
964 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000965
Chris Lattner0a8191e2010-01-05 07:50:36 +0000966 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
967 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
968 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +0000969 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +0000971 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000972 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000973 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000974 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000975 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +0000976
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 bool Op0Ordered;
978 bool Op1Ordered;
979 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
980 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +0000981 // uno && ord -> false
982 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
983 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000984 if (Op1Pred == 0) {
985 std::swap(LHS, RHS);
986 std::swap(Op0Pred, Op1Pred);
987 std::swap(Op0Ordered, Op1Ordered);
988 }
989 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +0000990 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +0000991 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +0000992 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
993 return LHS;
994 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +0000995 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +0000996
Chris Lattner0a8191e2010-01-05 07:50:36 +0000997 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +0000999 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001000 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001001 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001002 }
1003 }
1004
1005 return 0;
1006}
1007
1008
1009Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001010 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1012
1013 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1014 return ReplaceInstUsesWith(I, V);
1015
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001016 // (A|B)&(A|C) -> A|(B&C) etc
1017 if (Value *V = SimplifyUsingDistributiveLaws(I))
1018 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001019
Craig Topper9d4171a2012-12-20 07:09:41 +00001020 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 // purpose is to compute bits we don't care about.
1022 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001023 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024
1025 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1026 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001027
1028 // Optimize a variety of ((val OP C1) & C2) combinations...
1029 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1030 Value *Op0LHS = Op0I->getOperand(0);
1031 Value *Op0RHS = Op0I->getOperand(1);
1032 switch (Op0I->getOpcode()) {
1033 default: break;
1034 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001035 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001036 // If the mask is only needed on one incoming arm, push it up.
1037 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001038
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001039 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001040 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1041 // Not masking anything out for the LHS, move to RHS.
1042 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1043 Op0RHS->getName()+".masked");
1044 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1045 }
1046 if (!isa<Constant>(Op0RHS) &&
1047 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1048 // Not masking anything out for the RHS, move to LHS.
1049 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1050 Op0LHS->getName()+".masked");
1051 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1052 }
1053
1054 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001055 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001056 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001057 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1058 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1059 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001060 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1061 return BinaryOperator::CreateAnd(V, AndRHS);
1062 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1063 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1064 break;
1065
1066 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001067 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1068 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1069 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001070 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1071 return BinaryOperator::CreateAnd(V, AndRHS);
1072
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001073 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001074 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001075 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001076 uint32_t BitWidth = AndRHSMask.getBitWidth();
1077 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1078 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1079
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001080 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001081 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1082 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1083 }
1084 }
1085 break;
1086
1087 case Instruction::Shl:
1088 case Instruction::LShr:
1089 // (1 << x) & 1 --> zext(x == 0)
1090 // (1 >> x) & 1 --> zext(x == 0)
1091 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1092 Value *NewICmp =
1093 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1094 return new ZExtInst(NewICmp, I.getType());
1095 }
1096 break;
1097 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001098
Chris Lattner0a8191e2010-01-05 07:50:36 +00001099 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1100 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1101 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001102 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001103
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001104 // If this is an integer truncation, and if the source is an 'and' with
1105 // immediate, transform it. This frequently occurs for bitfield accesses.
1106 {
1107 Value *X = 0; ConstantInt *YC = 0;
1108 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1109 // Change: and (trunc (and X, YC) to T), C2
1110 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001111 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001112 // other simplifications.
1113 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1114 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1115 C3 = ConstantExpr::getAnd(C3, AndRHS);
1116 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117 }
1118 }
1119
1120 // Try to fold constant and into select arguments.
1121 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1122 if (Instruction *R = FoldOpIntoSelect(I, SI))
1123 return R;
1124 if (isa<PHINode>(Op0))
1125 if (Instruction *NV = FoldOpIntoPhi(I))
1126 return NV;
1127 }
1128
1129
1130 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1131 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1132 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1133 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1134 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1135 I.getName()+".demorgan");
1136 return BinaryOperator::CreateNot(Or);
1137 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001138
Chris Lattner0a8191e2010-01-05 07:50:36 +00001139 {
1140 Value *A = 0, *B = 0, *C = 0, *D = 0;
1141 // (A|B) & ~(A&B) -> A^B
1142 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1143 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1144 ((A == C && B == D) || (A == D && B == C)))
1145 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001146
Chris Lattner0a8191e2010-01-05 07:50:36 +00001147 // ~(A&B) & (A|B) -> A^B
1148 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1149 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1150 ((A == C && B == D) || (A == D && B == C)))
1151 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001152
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001153 // A&(A^B) => A & ~B
1154 {
1155 Value *tmpOp0 = Op0;
1156 Value *tmpOp1 = Op1;
1157 if (Op0->hasOneUse() &&
1158 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1159 if (A == Op1 || B == Op1 ) {
1160 tmpOp1 = Op0;
1161 tmpOp0 = Op1;
1162 // Simplify below
1163 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001164 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001166 if (tmpOp1->hasOneUse() &&
1167 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1168 if (B == tmpOp0) {
1169 std::swap(A, B);
1170 }
1171 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1172 // A is originally -1 (or a vector of -1 and undefs), then we enter
1173 // an endless loop. By checking that A is non-constant we ensure that
1174 // we will never get to the loop.
1175 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001176 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001177 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001178 }
1179
1180 // (A&((~A)|B)) -> A&B
1181 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1182 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1183 return BinaryOperator::CreateAnd(A, Op1);
1184 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1185 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1186 return BinaryOperator::CreateAnd(A, Op0);
1187 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001188
Chris Lattner0a8191e2010-01-05 07:50:36 +00001189 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1190 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001191 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1192 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001193
Chris Lattner4e8137d2010-02-11 06:26:33 +00001194 // If and'ing two fcmp, try combine them into one.
1195 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1196 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001197 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1198 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001199
1200
Chris Lattner0a8191e2010-01-05 07:50:36 +00001201 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1202 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001203 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001204 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001205 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1206 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001207 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001208 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001209
Chris Lattner4e8137d2010-02-11 06:26:33 +00001210 // Only do this if the casts both really cause code to be generated.
1211 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1212 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1213 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001214 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1215 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001216
Chris Lattner4e8137d2010-02-11 06:26:33 +00001217 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1218 // cast is otherwise not optimizable. This happens for vector sexts.
1219 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1220 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001221 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001222 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001223
Chris Lattner4e8137d2010-02-11 06:26:33 +00001224 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1225 // cast is otherwise not optimizable. This happens for vector sexts.
1226 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1227 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001228 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001229 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001230 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001231 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001232
Chris Lattner0a8191e2010-01-05 07:50:36 +00001233 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1234 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1235 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001236 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001237 SI0->getOperand(1) == SI1->getOperand(1) &&
1238 (SI0->hasOneUse() || SI1->hasOneUse())) {
1239 Value *NewOp =
1240 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1241 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001242 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001243 SI1->getOperand(1));
1244 }
1245 }
1246
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001247 {
1248 Value *X = 0;
1249 bool OpsSwapped = false;
1250 // Canonicalize SExt or Not to the LHS
1251 if (match(Op1, m_SExt(m_Value())) ||
1252 match(Op1, m_Not(m_Value()))) {
1253 std::swap(Op0, Op1);
1254 OpsSwapped = true;
1255 }
1256
1257 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1258 if (match(Op0, m_SExt(m_Value(X))) &&
1259 X->getType()->getScalarType()->isIntegerTy(1)) {
1260 Value *Zero = Constant::getNullValue(Op1->getType());
1261 return SelectInst::Create(X, Op1, Zero);
1262 }
1263
1264 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1265 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1266 X->getType()->getScalarType()->isIntegerTy(1)) {
1267 Value *Zero = Constant::getNullValue(Op0->getType());
1268 return SelectInst::Create(X, Zero, Op1);
1269 }
1270
1271 if (OpsSwapped)
1272 std::swap(Op0, Op1);
1273 }
1274
Chris Lattner0a8191e2010-01-05 07:50:36 +00001275 return Changed ? &I : 0;
1276}
1277
1278/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1279/// capable of providing pieces of a bswap. The subexpression provides pieces
1280/// of a bswap if it is proven that each of the non-zero bytes in the output of
1281/// the expression came from the corresponding "byte swapped" byte in some other
1282/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1283/// we know that the expression deposits the low byte of %X into the high byte
1284/// of the bswap result and that all other bytes are zero. This expression is
1285/// accepted, the high byte of ByteValues is set to X to indicate a correct
1286/// match.
1287///
1288/// This function returns true if the match was unsuccessful and false if so.
1289/// On entry to the function the "OverallLeftShift" is a signed integer value
1290/// indicating the number of bytes that the subexpression is later shifted. For
1291/// example, if the expression is later right shifted by 16 bits, the
1292/// OverallLeftShift value would be -2 on entry. This is used to specify which
1293/// byte of ByteValues is actually being set.
1294///
1295/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1296/// byte is masked to zero by a user. For example, in (X & 255), X will be
1297/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1298/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1299/// always in the local (OverallLeftShift) coordinate space.
1300///
1301static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1302 SmallVector<Value*, 8> &ByteValues) {
1303 if (Instruction *I = dyn_cast<Instruction>(V)) {
1304 // If this is an or instruction, it may be an inner node of the bswap.
1305 if (I->getOpcode() == Instruction::Or) {
1306 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1307 ByteValues) ||
1308 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1309 ByteValues);
1310 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001311
Chris Lattner0a8191e2010-01-05 07:50:36 +00001312 // If this is a logical shift by a constant multiple of 8, recurse with
1313 // OverallLeftShift and ByteMask adjusted.
1314 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001315 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001316 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1317 // Ensure the shift amount is defined and of a byte value.
1318 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1319 return true;
1320
1321 unsigned ByteShift = ShAmt >> 3;
1322 if (I->getOpcode() == Instruction::Shl) {
1323 // X << 2 -> collect(X, +2)
1324 OverallLeftShift += ByteShift;
1325 ByteMask >>= ByteShift;
1326 } else {
1327 // X >>u 2 -> collect(X, -2)
1328 OverallLeftShift -= ByteShift;
1329 ByteMask <<= ByteShift;
1330 ByteMask &= (~0U >> (32-ByteValues.size()));
1331 }
1332
1333 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1334 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1335
Craig Topper9d4171a2012-12-20 07:09:41 +00001336 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001337 ByteValues);
1338 }
1339
1340 // If this is a logical 'and' with a mask that clears bytes, clear the
1341 // corresponding bytes in ByteMask.
1342 if (I->getOpcode() == Instruction::And &&
1343 isa<ConstantInt>(I->getOperand(1))) {
1344 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1345 unsigned NumBytes = ByteValues.size();
1346 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1347 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001348
Chris Lattner0a8191e2010-01-05 07:50:36 +00001349 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1350 // If this byte is masked out by a later operation, we don't care what
1351 // the and mask is.
1352 if ((ByteMask & (1 << i)) == 0)
1353 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001354
Chris Lattner0a8191e2010-01-05 07:50:36 +00001355 // If the AndMask is all zeros for this byte, clear the bit.
1356 APInt MaskB = AndMask & Byte;
1357 if (MaskB == 0) {
1358 ByteMask &= ~(1U << i);
1359 continue;
1360 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001361
Chris Lattner0a8191e2010-01-05 07:50:36 +00001362 // If the AndMask is not all ones for this byte, it's not a bytezap.
1363 if (MaskB != Byte)
1364 return true;
1365
1366 // Otherwise, this byte is kept.
1367 }
1368
Craig Topper9d4171a2012-12-20 07:09:41 +00001369 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001370 ByteValues);
1371 }
1372 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001373
Chris Lattner0a8191e2010-01-05 07:50:36 +00001374 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1375 // the input value to the bswap. Some observations: 1) if more than one byte
1376 // is demanded from this input, then it could not be successfully assembled
1377 // into a byteswap. At least one of the two bytes would not be aligned with
1378 // their ultimate destination.
1379 if (!isPowerOf2_32(ByteMask)) return true;
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001380 unsigned InputByteNo = countTrailingZeros(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001381
Chris Lattner0a8191e2010-01-05 07:50:36 +00001382 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1383 // is demanded, it needs to go into byte 0 of the result. This means that the
1384 // byte needs to be shifted until it lands in the right byte bucket. The
1385 // shift amount depends on the position: if the byte is coming from the high
1386 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1387 // low part, it must be shifted left.
1388 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001389 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1390 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001391
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 // If the destination byte value is already defined, the values are or'd
1393 // together, which isn't a bswap (unless it's an or of the same bits).
1394 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1395 return true;
1396 ByteValues[DestByteNo] = V;
1397 return false;
1398}
1399
1400/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1401/// If so, insert the new bswap intrinsic and return it.
1402Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001403 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001404 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001406 ITy->getBitWidth() > 32*8)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001407 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001408
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 /// ByteValues - For each byte of the result, we keep track of which value
1410 /// defines each byte.
1411 SmallVector<Value*, 8> ByteValues;
1412 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001413
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 // Try to find all the pieces corresponding to the bswap.
1415 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1416 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1417 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001418
Chris Lattner0a8191e2010-01-05 07:50:36 +00001419 // Check to see if all of the bytes come from the same value.
1420 Value *V = ByteValues[0];
1421 if (V == 0) return 0; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001422
Chris Lattner0a8191e2010-01-05 07:50:36 +00001423 // Check to make sure that all of the bytes come from the same value.
1424 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1425 if (ByteValues[i] != V)
1426 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001427 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001428 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001429 return CallInst::Create(F, V);
1430}
1431
1432/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1433/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1434/// we can simplify this expression to "cond ? C : D or B".
1435static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1436 Value *C, Value *D) {
1437 // If A is not a select of -1/0, this cannot match.
1438 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001439 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001440 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001441 return 0;
1442
1443 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001444 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001445 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001446 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001447 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001448
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001450 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001451 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001452 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001453 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001454 return 0;
1455}
1456
Chris Lattner067459c2010-03-05 08:46:26 +00001457/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1458Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001459 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1460
1461 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1462 if (PredicatesFoldable(LHSCC, RHSCC)) {
1463 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1464 LHS->getOperand(1) == RHS->getOperand(0))
1465 LHS->swapOperands();
1466 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1467 LHS->getOperand(1) == RHS->getOperand(1)) {
1468 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1469 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1470 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001471 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001472 }
1473 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001474
1475 // handle (roughly):
1476 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1477 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1478 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001479
Chris Lattner0a8191e2010-01-05 07:50:36 +00001480 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1481 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1482 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
David Majnemerc2a990b2013-07-05 00:31:17 +00001483
1484 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1485 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1486 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1487 Value *A = 0, *B = 0;
1488 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1489 B = Val;
1490 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1491 A = Val2;
1492 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1493 A = RHS->getOperand(1);
1494 }
1495 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1496 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1497 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1498 B = Val2;
1499 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1500 A = Val;
1501 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1502 A = LHS->getOperand(1);
1503 }
1504 if (A && B)
1505 return Builder->CreateICmp(
1506 ICmpInst::ICMP_UGE,
1507 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1508 }
1509
1510 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner0a8191e2010-01-05 07:50:36 +00001511 if (LHSCst == 0 || RHSCst == 0) return 0;
1512
Owen Anderson8f306a72010-08-02 09:32:13 +00001513 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1514 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1515 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1516 Value *NewOr = Builder->CreateOr(Val, Val2);
1517 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1518 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001519 }
1520
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001521 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001522 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001523 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001524 ConstantInt *AddCst;
1525 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1526 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001527 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001528 }
1529
Chris Lattner0a8191e2010-01-05 07:50:36 +00001530 // From here on, we only handle:
1531 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1532 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001533
Chris Lattner0a8191e2010-01-05 07:50:36 +00001534 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1535 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1536 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1537 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1538 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1539 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001540
Chris Lattner0a8191e2010-01-05 07:50:36 +00001541 // We can't fold (ugt x, C) | (sgt x, C2).
1542 if (!PredicatesFoldable(LHSCC, RHSCC))
1543 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001544
Chris Lattner0a8191e2010-01-05 07:50:36 +00001545 // Ensure that the larger constant is on the RHS.
1546 bool ShouldSwap;
1547 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001548 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001549 CmpInst::isSigned(RHSCC)))
1550 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1551 else
1552 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001553
Chris Lattner0a8191e2010-01-05 07:50:36 +00001554 if (ShouldSwap) {
1555 std::swap(LHS, RHS);
1556 std::swap(LHSCst, RHSCst);
1557 std::swap(LHSCC, RHSCC);
1558 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001559
Dan Gohman4a618822010-02-10 16:03:48 +00001560 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001561 // comparing a value against two constants and or'ing the result
1562 // together. Because of the above check, we know that we only have
1563 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1564 // icmp folding check above), that the two constants are not
1565 // equal.
1566 assert(LHSCst != RHSCst && "Compares not folded above?");
1567
1568 switch (LHSCC) {
1569 default: llvm_unreachable("Unknown integer condition code!");
1570 case ICmpInst::ICMP_EQ:
1571 switch (RHSCC) {
1572 default: llvm_unreachable("Unknown integer condition code!");
1573 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001574 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001575 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001576 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001577 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1578
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001579 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1580 if (Xor.isPowerOf2()) {
1581 Value *NegCst = Builder->getInt(~Xor);
1582 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1583 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1584 }
1585 }
1586
David Majnemer1fae1952013-04-14 21:15:43 +00001587 if (LHSCst == SubOne(RHSCst)) {
1588 // (X == 13 | X == 14) -> X-13 <u 2
1589 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1590 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1591 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1592 return Builder->CreateICmpULT(Add, AddCST);
1593 }
1594
Chris Lattner0a8191e2010-01-05 07:50:36 +00001595 break; // (X == 13 | X == 15) -> no change
1596 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1597 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1598 break;
1599 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1600 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1601 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001602 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001603 }
1604 break;
1605 case ICmpInst::ICMP_NE:
1606 switch (RHSCC) {
1607 default: llvm_unreachable("Unknown integer condition code!");
1608 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1609 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1610 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001611 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001612 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1613 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1614 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001615 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001616 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001617 case ICmpInst::ICMP_ULT:
1618 switch (RHSCC) {
1619 default: llvm_unreachable("Unknown integer condition code!");
1620 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1621 break;
1622 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1623 // If RHSCst is [us]MAXINT, it is always false. Not handling
1624 // this can cause overflow.
1625 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001626 return LHS;
1627 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001628 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1629 break;
1630 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1631 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001632 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001633 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1634 break;
1635 }
1636 break;
1637 case ICmpInst::ICMP_SLT:
1638 switch (RHSCC) {
1639 default: llvm_unreachable("Unknown integer condition code!");
1640 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1641 break;
1642 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1643 // If RHSCst is [us]MAXINT, it is always false. Not handling
1644 // this can cause overflow.
1645 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001646 return LHS;
1647 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001648 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1649 break;
1650 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1651 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001652 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001653 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1654 break;
1655 }
1656 break;
1657 case ICmpInst::ICMP_UGT:
1658 switch (RHSCC) {
1659 default: llvm_unreachable("Unknown integer condition code!");
1660 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1661 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001662 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001663 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1664 break;
1665 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1666 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001667 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001668 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1669 break;
1670 }
1671 break;
1672 case ICmpInst::ICMP_SGT:
1673 switch (RHSCC) {
1674 default: llvm_unreachable("Unknown integer condition code!");
1675 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1676 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001677 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001678 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1679 break;
1680 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1681 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001682 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001683 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1684 break;
1685 }
1686 break;
1687 }
1688 return 0;
1689}
1690
Chris Lattner067459c2010-03-05 08:46:26 +00001691/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1692/// instcombine, this returns a Value which should already be inserted into the
1693/// function.
1694Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001695 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001696 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001697 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1698 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1699 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1700 // If either of the constants are nans, then the whole thing returns
1701 // true.
1702 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001703 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001704
Chris Lattner0a8191e2010-01-05 07:50:36 +00001705 // Otherwise, no need to compare the two constants, compare the
1706 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001707 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001708 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001709
Chris Lattner0a8191e2010-01-05 07:50:36 +00001710 // Handle vector zeros. This occurs because the canonical form of
1711 // "fcmp uno x,x" is "fcmp uno x, 0".
1712 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1713 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001714 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001715
Chris Lattner0a8191e2010-01-05 07:50:36 +00001716 return 0;
1717 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001718
Chris Lattner0a8191e2010-01-05 07:50:36 +00001719 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1720 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1721 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001722
Chris Lattner0a8191e2010-01-05 07:50:36 +00001723 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1724 // Swap RHS operands to match LHS.
1725 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1726 std::swap(Op1LHS, Op1RHS);
1727 }
1728 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1729 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1730 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001731 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001732 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001733 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001734 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001735 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001736 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001737 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001738 bool Op0Ordered;
1739 bool Op1Ordered;
1740 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1741 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1742 if (Op0Ordered == Op1Ordered) {
1743 // If both are ordered or unordered, return a new fcmp with
1744 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001745 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001746 }
1747 }
1748 return 0;
1749}
1750
1751/// FoldOrWithConstants - This helper function folds:
1752///
1753/// ((A | B) & C1) | (B & C2)
1754///
1755/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001756///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757/// (A & C1) | B
1758///
1759/// when the XOR of the two constants is "all ones" (-1).
1760Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1761 Value *A, Value *B, Value *C) {
1762 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1763 if (!CI1) return 0;
1764
1765 Value *V1 = 0;
1766 ConstantInt *CI2 = 0;
1767 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1768
1769 APInt Xor = CI1->getValue() ^ CI2->getValue();
1770 if (!Xor.isAllOnesValue()) return 0;
1771
1772 if (V1 == A || V1 == B) {
1773 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1774 return BinaryOperator::CreateOr(NewOp, V1);
1775 }
1776
1777 return 0;
1778}
1779
1780Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001781 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1783
1784 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1785 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001786
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001787 // (A&B)|(A&C) -> A&(B|C) etc
1788 if (Value *V = SimplifyUsingDistributiveLaws(I))
1789 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001790
Craig Topper9d4171a2012-12-20 07:09:41 +00001791 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 // purpose is to compute bits we don't care about.
1793 if (SimplifyDemandedInstructionBits(I))
1794 return &I;
1795
1796 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1797 ConstantInt *C1 = 0; Value *X = 0;
1798 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001799 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001800 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001801 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001802 Op0->hasOneUse()) {
1803 Value *Or = Builder->CreateOr(X, RHS);
1804 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001805 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001806 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001807 }
1808
1809 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1810 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1811 Op0->hasOneUse()) {
1812 Value *Or = Builder->CreateOr(X, RHS);
1813 Or->takeName(Op0);
1814 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001815 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816 }
1817
1818 // Try to fold constant and into select arguments.
1819 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1820 if (Instruction *R = FoldOpIntoSelect(I, SI))
1821 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001822
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 if (isa<PHINode>(Op0))
1824 if (Instruction *NV = FoldOpIntoPhi(I))
1825 return NV;
1826 }
1827
1828 Value *A = 0, *B = 0;
1829 ConstantInt *C1 = 0, *C2 = 0;
1830
1831 // (A | B) | C and A | (B | C) -> bswap if possible.
1832 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1833 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1834 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001835 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1836 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001837 if (Instruction *BSwap = MatchBSwap(I))
1838 return BSwap;
1839 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001840
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001841 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842 if (Op0->hasOneUse() &&
1843 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1844 MaskedValueIsZero(Op1, C1->getValue())) {
1845 Value *NOr = Builder->CreateOr(A, Op1);
1846 NOr->takeName(Op0);
1847 return BinaryOperator::CreateXor(NOr, C1);
1848 }
1849
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001850 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001851 if (Op1->hasOneUse() &&
1852 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1853 MaskedValueIsZero(Op0, C1->getValue())) {
1854 Value *NOr = Builder->CreateOr(A, Op0);
1855 NOr->takeName(Op0);
1856 return BinaryOperator::CreateXor(NOr, C1);
1857 }
1858
1859 // (A & C)|(B & D)
1860 Value *C = 0, *D = 0;
1861 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1862 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001863 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001864 C1 = dyn_cast<ConstantInt>(C);
1865 C2 = dyn_cast<ConstantInt>(D);
1866 if (C1 && C2) { // (A & C1)|(B & C2)
1867 // If we have: ((V + N) & C1) | (V & C2)
1868 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1869 // replace with V+N.
1870 if (C1->getValue() == ~C2->getValue()) {
1871 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1872 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1873 // Add commutes, try both ways.
1874 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1875 return ReplaceInstUsesWith(I, A);
1876 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1877 return ReplaceInstUsesWith(I, A);
1878 }
1879 // Or commutes, try both ways.
1880 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1881 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1882 // Add commutes, try both ways.
1883 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1884 return ReplaceInstUsesWith(I, B);
1885 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1886 return ReplaceInstUsesWith(I, B);
1887 }
1888 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001889
Chris Lattner0a8191e2010-01-05 07:50:36 +00001890 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00001891 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001892 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001893 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1894 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1895 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1896 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001897 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001898 // Or commutes, try both ways.
1899 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1900 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1901 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1902 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001903 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001904
Chris Lattner95188692010-01-11 06:55:24 +00001905 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001906 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Chris Lattner95188692010-01-11 06:55:24 +00001907 ConstantInt *C3 = 0, *C4 = 0;
1908 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1909 (C3->getValue() & ~C1->getValue()) == 0 &&
1910 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1911 (C4->getValue() & ~C2->getValue()) == 0) {
1912 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1913 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001914 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001915 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001916 }
1917 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001918
Chris Lattner8e2c4712010-02-02 02:43:51 +00001919 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1920 // Don't do this for vector select idioms, the code generator doesn't handle
1921 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00001922 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00001923 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1924 return Match;
1925 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1926 return Match;
1927 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1928 return Match;
1929 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1930 return Match;
1931 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001932
1933 // ((A&~B)|(~A&B)) -> A^B
1934 if ((match(C, m_Not(m_Specific(D))) &&
1935 match(B, m_Not(m_Specific(A)))))
1936 return BinaryOperator::CreateXor(A, D);
1937 // ((~B&A)|(~A&B)) -> A^B
1938 if ((match(A, m_Not(m_Specific(D))) &&
1939 match(B, m_Not(m_Specific(C)))))
1940 return BinaryOperator::CreateXor(C, D);
1941 // ((A&~B)|(B&~A)) -> A^B
1942 if ((match(C, m_Not(m_Specific(B))) &&
1943 match(D, m_Not(m_Specific(A)))))
1944 return BinaryOperator::CreateXor(A, B);
1945 // ((~B&A)|(B&~A)) -> A^B
1946 if ((match(A, m_Not(m_Specific(B))) &&
1947 match(D, m_Not(m_Specific(C)))))
1948 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00001949
1950 // ((A|B)&1)|(B&-2) -> (A&1) | B
1951 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1952 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1953 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1954 if (Ret) return Ret;
1955 }
1956 // (B&-2)|((A|B)&1) -> (A&1) | B
1957 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1958 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1959 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1960 if (Ret) return Ret;
1961 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001962 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001963
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1965 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1966 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001967 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001968 SI0->getOperand(1) == SI1->getOperand(1) &&
1969 (SI0->hasOneUse() || SI1->hasOneUse())) {
1970 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1971 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001972 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001973 SI1->getOperand(1));
1974 }
1975 }
1976
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1978 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1979 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1980 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1981 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1982 I.getName()+".demorgan");
1983 return BinaryOperator::CreateNot(And);
1984 }
1985
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001986 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00001987 bool SwappedForXor = false;
1988 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001989 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00001990 SwappedForXor = true;
1991 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001992
1993 // A | ( A ^ B) -> A | B
1994 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00001995 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001996 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1997 if (Op0 == A || Op0 == B)
1998 return BinaryOperator::CreateOr(A, B);
1999
Chad Rosier7813dce2012-04-26 23:29:14 +00002000 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2001 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2002 return BinaryOperator::CreateOr(A, B);
2003
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002004 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2005 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2006 return BinaryOperator::CreateOr(Not, Op0);
2007 }
2008 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2009 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2010 return BinaryOperator::CreateOr(Not, Op0);
2011 }
2012 }
2013
2014 // A | ~(A | B) -> A | ~B
2015 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002016 if (match(Op1, m_Not(m_Value(A))))
2017 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002018 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2019 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2020 B->getOpcode() == Instruction::Xor)) {
2021 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2022 B->getOperand(0);
2023 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2024 return BinaryOperator::CreateOr(Not, Op0);
2025 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002026
Eli Friedmane06535b2012-03-16 00:52:42 +00002027 if (SwappedForXor)
2028 std::swap(Op0, Op1);
2029
Chris Lattner0a8191e2010-01-05 07:50:36 +00002030 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2031 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00002032 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2033 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002034
Chris Lattner4e8137d2010-02-11 06:26:33 +00002035 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2036 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2037 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002038 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2039 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002040
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2042 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002043 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2044 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002045 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002046 if (SrcTy == Op1C->getOperand(0)->getType() &&
2047 SrcTy->isIntOrIntVectorTy()) {
2048 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002049
Chris Lattner311aa632011-01-15 05:40:29 +00002050 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2051 // Only do this if the casts both really cause code to be
2052 // generated.
2053 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2054 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2055 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2056 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002057 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002058
Chris Lattner311aa632011-01-15 05:40:29 +00002059 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2060 // cast is otherwise not optimizable. This happens for vector sexts.
2061 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2062 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2063 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2064 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002065
Chris Lattner311aa632011-01-15 05:40:29 +00002066 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2067 // cast is otherwise not optimizable. This happens for vector sexts.
2068 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2069 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2070 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2071 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002072 }
Chris Lattner311aa632011-01-15 05:40:29 +00002073 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002074 }
Eli Friedman23956262011-04-14 22:41:27 +00002075
2076 // or(sext(A), B) -> A ? -1 : B where A is an i1
2077 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2078 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2079 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2080 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2081 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2082
Owen Andersonc237a842010-09-13 17:59:27 +00002083 // Note: If we've gotten to the point of visiting the outer OR, then the
2084 // inner one couldn't be simplified. If it was a constant, then it won't
2085 // be simplified by a later pass either, so we try swapping the inner/outer
2086 // ORs in the hopes that we'll be able to simplify it this way.
2087 // (X|C) | V --> (X|V) | C
2088 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2089 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2090 Value *Inner = Builder->CreateOr(A, Op1);
2091 Inner->takeName(Op0);
2092 return BinaryOperator::CreateOr(Inner, C1);
2093 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002094
Bill Wendling23242092013-02-16 23:41:36 +00002095 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2096 // Since this OR statement hasn't been optimized further yet, we hope
2097 // that this transformation will allow the new ORs to be optimized.
2098 {
2099 Value *X = 0, *Y = 0;
2100 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2101 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2102 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2103 Value *orTrue = Builder->CreateOr(A, C);
2104 Value *orFalse = Builder->CreateOr(B, D);
2105 return SelectInst::Create(X, orTrue, orFalse);
2106 }
2107 }
2108
Chris Lattner0a8191e2010-01-05 07:50:36 +00002109 return Changed ? &I : 0;
2110}
2111
2112Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002113 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2115
Duncan Sandsc89ac072010-11-17 18:52:15 +00002116 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2117 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002118
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002119 // (A&B)^(A&C) -> A&(B^C) etc
2120 if (Value *V = SimplifyUsingDistributiveLaws(I))
2121 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002122
Craig Topper9d4171a2012-12-20 07:09:41 +00002123 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002124 // purpose is to compute bits we don't care about.
2125 if (SimplifyDemandedInstructionBits(I))
2126 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002127
2128 // Is this a ~ operation?
2129 if (Value *NotOp = dyn_castNotVal(&I)) {
2130 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002131 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002132 Op0I->getOpcode() == Instruction::Or) {
2133 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2134 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2135 if (dyn_castNotVal(Op0I->getOperand(1)))
2136 Op0I->swapOperands();
2137 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2138 Value *NotY =
2139 Builder->CreateNot(Op0I->getOperand(1),
2140 Op0I->getOperand(1)->getName()+".not");
2141 if (Op0I->getOpcode() == Instruction::And)
2142 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2143 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2144 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002145
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2147 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002148 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002149 isFreeToInvert(Op0I->getOperand(1))) {
2150 Value *NotX =
2151 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2152 Value *NotY =
2153 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2154 if (Op0I->getOpcode() == Instruction::And)
2155 return BinaryOperator::CreateOr(NotX, NotY);
2156 return BinaryOperator::CreateAnd(NotX, NotY);
2157 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002158
2159 } else if (Op0I->getOpcode() == Instruction::AShr) {
2160 // ~(~X >>s Y) --> (X >>s Y)
2161 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2162 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002163 }
2164 }
2165 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002166
2167
Chris Lattner0a8191e2010-01-05 07:50:36 +00002168 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002169 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002170 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002171 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2172 return CmpInst::Create(CI->getOpcode(),
2173 CI->getInversePredicate(),
2174 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002175
2176 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2177 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2178 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2179 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2180 Instruction::CastOps Opcode = Op0C->getOpcode();
2181 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002182 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002183 Op0C->getDestTy()))) {
2184 CI->setPredicate(CI->getInversePredicate());
2185 return CastInst::Create(Opcode, CI, Op0C->getType());
2186 }
2187 }
2188 }
2189 }
2190
2191 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2192 // ~(c-X) == X-c-1 == X+(-c-1)
2193 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2194 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2195 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2196 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2197 ConstantInt::get(I.getType(), 1));
2198 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2199 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002200
Chris Lattner0a8191e2010-01-05 07:50:36 +00002201 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2202 if (Op0I->getOpcode() == Instruction::Add) {
2203 // ~(X-c) --> (-c-1)-X
2204 if (RHS->isAllOnesValue()) {
2205 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2206 return BinaryOperator::CreateSub(
2207 ConstantExpr::getSub(NegOp0CI,
2208 ConstantInt::get(I.getType(), 1)),
2209 Op0I->getOperand(0));
2210 } else if (RHS->getValue().isSignBit()) {
2211 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002212 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002213 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2214
2215 }
2216 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002217 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002218 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2219 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2220 // Anything in both C1 and C2 is known to be zero, remove it from
2221 // NewRHS.
2222 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002223 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002224 ConstantExpr::getNot(CommonBits));
2225 Worklist.Add(Op0I);
2226 I.setOperand(0, Op0I->getOperand(0));
2227 I.setOperand(1, NewRHS);
2228 return &I;
2229 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002230 } else if (Op0I->getOpcode() == Instruction::LShr) {
2231 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2232 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002233 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002234 ConstantInt *C1;
2235 if (Op0I->hasOneUse() &&
2236 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2237 E1->getOpcode() == Instruction::Xor &&
2238 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2239 // fold (C1 >> C2) ^ C3
2240 ConstantInt *C2 = Op0CI, *C3 = RHS;
2241 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2242 FoldConst ^= C3->getValue();
2243 // Prepare the two operands.
2244 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2245 Opnd0->takeName(Op0I);
2246 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2247 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2248
2249 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2250 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002251 }
2252 }
2253 }
2254
2255 // Try to fold constant and into select arguments.
2256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2257 if (Instruction *R = FoldOpIntoSelect(I, SI))
2258 return R;
2259 if (isa<PHINode>(Op0))
2260 if (Instruction *NV = FoldOpIntoPhi(I))
2261 return NV;
2262 }
2263
Chris Lattner0a8191e2010-01-05 07:50:36 +00002264 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2265 if (Op1I) {
2266 Value *A, *B;
2267 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2268 if (A == Op0) { // B^(B|A) == (A|B)^B
2269 Op1I->swapOperands();
2270 I.swapOperands();
2271 std::swap(Op0, Op1);
2272 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2273 I.swapOperands(); // Simplified below.
2274 std::swap(Op0, Op1);
2275 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002276 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002277 Op1I->hasOneUse()){
2278 if (A == Op0) { // A^(A&B) -> A^(B&A)
2279 Op1I->swapOperands();
2280 std::swap(A, B);
2281 }
2282 if (B == Op0) { // A^(B&A) -> (B&A)^A
2283 I.swapOperands(); // Simplified below.
2284 std::swap(Op0, Op1);
2285 }
2286 }
2287 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002288
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2290 if (Op0I) {
2291 Value *A, *B;
2292 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2293 Op0I->hasOneUse()) {
2294 if (A == Op1) // (B|A)^B == (A|B)^B
2295 std::swap(A, B);
2296 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002297 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002298 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002299 Op0I->hasOneUse()){
2300 if (A == Op1) // (A&B)^A -> (B&A)^A
2301 std::swap(A, B);
2302 if (B == Op1 && // (B&A)^A == ~B & A
2303 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002304 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002305 }
2306 }
2307 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002308
Chris Lattner0a8191e2010-01-05 07:50:36 +00002309 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Craig Topper9d4171a2012-12-20 07:09:41 +00002310 if (Op0I && Op1I && Op0I->isShift() &&
2311 Op0I->getOpcode() == Op1I->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002312 Op0I->getOperand(1) == Op1I->getOperand(1) &&
Benjamin Kramer9d5849f2012-05-28 20:52:48 +00002313 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002314 Value *NewOp =
2315 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2316 Op0I->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002317 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002318 Op1I->getOperand(1));
2319 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002320
Chris Lattner0a8191e2010-01-05 07:50:36 +00002321 if (Op0I && Op1I) {
2322 Value *A, *B, *C, *D;
2323 // (A & B)^(A | B) -> A ^ B
2324 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2325 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002326 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002327 return BinaryOperator::CreateXor(A, B);
2328 }
2329 // (A | B)^(A & B) -> A ^ B
2330 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2331 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002332 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002333 return BinaryOperator::CreateXor(A, B);
2334 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002335 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002336
Chris Lattner0a8191e2010-01-05 07:50:36 +00002337 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2338 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2339 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2340 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2341 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2342 LHS->getOperand(1) == RHS->getOperand(0))
2343 LHS->swapOperands();
2344 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2345 LHS->getOperand(1) == RHS->getOperand(1)) {
2346 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2347 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2348 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002349 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002350 getNewICmpValue(isSigned, Code, Op0, Op1,
2351 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002352 }
2353 }
2354
2355 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2356 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2357 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2358 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002359 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002360 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002361 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002362 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002363 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002364 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002365 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002366 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2367 Op1C->getOperand(0), I.getName());
2368 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2369 }
2370 }
2371 }
2372
2373 return Changed ? &I : 0;
2374}