blob: c1e60d4c427b3c50e9a23a1607cf0406c1422f17 [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.
25static Constant *AddOne(Constant *C) {
26 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
27}
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.
176 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
177
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.
183 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
184
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));
212 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
213 AndRHS->getValue() & ShlMask);
214
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000215 if (CI->getValue() == ShlMask)
216 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000217 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000218
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000219 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000220 TheAnd.setOperand(1, CI);
221 return &TheAnd;
222 }
223 break;
224 }
225 case Instruction::LShr: {
226 // We know that the AND will not produce any of the bits shifted in, so if
227 // the anded constant includes them, clear them now! This only applies to
228 // unsigned shifts, because a signed shr may bring in set bits!
229 //
230 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
231 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
232 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
233 ConstantInt *CI = ConstantInt::get(Op->getContext(),
234 AndRHS->getValue() & ShrMask);
235
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000236 if (CI->getValue() == ShrMask)
237 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000238 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000239
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000240 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000241 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
242 return &TheAnd;
243 }
244 break;
245 }
246 case Instruction::AShr:
247 // Signed shr.
248 // See if this is shifting in some sign extension, then masking it out
249 // with an and.
250 if (Op->hasOneUse()) {
251 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
252 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
253 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
254 Constant *C = ConstantInt::get(Op->getContext(),
255 AndRHS->getValue() & ShrMask);
256 if (C == AndRHS) { // Masking out bits shifted in.
257 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
258 // Make the argument unsigned.
259 Value *ShVal = Op->getOperand(0);
260 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
261 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
262 }
263 }
264 break;
265 }
266 return 0;
267}
268
269
270/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000271/// true, otherwise (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000272/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000273/// whether to treat the V, Lo and HI as signed or not. IB is the location to
274/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000275Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
276 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000277 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000278 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
279 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000280
Chris Lattner0a8191e2010-01-05 07:50:36 +0000281 if (Inside) {
282 if (Lo == Hi) // Trivially false.
Chris Lattner067459c2010-03-05 08:46:26 +0000283 return ConstantInt::getFalse(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000284
285 // V >= Min && V < Hi --> V < Hi
286 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000287 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000288 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000289 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000290 }
291
292 // Emit V-Lo <u Hi-Lo
293 Constant *NegLo = ConstantExpr::getNeg(Lo);
294 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
295 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000296 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000297 }
298
299 if (Lo == Hi) // Trivially true.
Chris Lattner067459c2010-03-05 08:46:26 +0000300 return ConstantInt::getTrue(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000301
302 // V < Min || V >= Hi -> V > Hi-1
303 Hi = SubOne(cast<ConstantInt>(Hi));
304 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000305 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000306 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000307 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000308 }
309
310 // Emit V-Lo >u Hi-1-Lo
311 // Note that Hi has already had one subtracted from it, above.
312 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
313 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
314 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000315 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000316}
317
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000318// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
Chris Lattner0a8191e2010-01-05 07:50:36 +0000319// any number of 0s on either side. The 1s are allowed to wrap from LSB to
320// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
321// not, since all 1s are not contiguous.
322static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
323 const APInt& V = Val->getValue();
324 uint32_t BitWidth = Val->getType()->getBitWidth();
325 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
326
327 // look for the first zero bit after the run of ones
328 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
329 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000330 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000331 return true;
332}
333
334/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
335/// where isSub determines whether the operator is a sub. If we can fold one of
336/// the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000337///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000338/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
339/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
340/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000341///
342/// return (A +/- B).
343///
344Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
345 ConstantInt *Mask, bool isSub,
346 Instruction &I) {
347 Instruction *LHSI = dyn_cast<Instruction>(LHS);
348 if (!LHSI || LHSI->getNumOperands() != 2 ||
349 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
350
351 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
352
353 switch (LHSI->getOpcode()) {
354 default: return 0;
355 case Instruction::And:
356 if (ConstantExpr::getAnd(N, Mask) == Mask) {
357 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000358 if ((Mask->getValue().countLeadingZeros() +
359 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000360 Mask->getValue().getBitWidth())
361 break;
362
363 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
364 // part, we don't need any explicit masks to take them out of A. If that
365 // is all N is, ignore it.
366 uint32_t MB = 0, ME = 0;
367 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
368 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
369 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
370 if (MaskedValueIsZero(RHS, Mask))
371 break;
372 }
373 }
374 return 0;
375 case Instruction::Or:
376 case Instruction::Xor:
377 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000378 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000379 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
380 && ConstantExpr::getAnd(N, Mask)->isNullValue())
381 break;
382 return 0;
383 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000384
Chris Lattner0a8191e2010-01-05 07:50:36 +0000385 if (isSub)
386 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
387 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
388}
389
Owen Anderson3fe002d2010-09-08 22:16:17 +0000390/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000391/// One of A and B is considered the mask, the other the value. This is
392/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000393/// contains only "Mask", then both A and B can be considered masks.
394/// If A is the mask, then it was proven, that (A & C) == C. This
395/// is trivial if C == A, or C == 0. If both A and C are constants, this
396/// proof is also easy.
397/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000398/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000399/// if (A & B) == A, or all bits of A are set in B.
400/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000401/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000402/// if (A & B) == 0, or all bits of A are cleared in B.
403/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000404/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000405/// contain any number of one bits and zero bits.
406/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
407/// The Part "Not" means, that in above descriptions "==" should be replaced
408/// by "!=".
409/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
410/// If the mask A contains a single bit, then the following is equivalent:
411/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
412/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
413enum MaskedICmpType {
414 FoldMskICmp_AMask_AllOnes = 1,
415 FoldMskICmp_AMask_NotAllOnes = 2,
416 FoldMskICmp_BMask_AllOnes = 4,
417 FoldMskICmp_BMask_NotAllOnes = 8,
418 FoldMskICmp_Mask_AllZeroes = 16,
419 FoldMskICmp_Mask_NotAllZeroes = 32,
420 FoldMskICmp_AMask_Mixed = 64,
421 FoldMskICmp_AMask_NotMixed = 128,
422 FoldMskICmp_BMask_Mixed = 256,
423 FoldMskICmp_BMask_NotMixed = 512
424};
425
426/// return the set of pattern classes (from MaskedICmpType)
427/// that (icmp SCC (A & B), C) satisfies
Craig Topper9d4171a2012-12-20 07:09:41 +0000428static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429 ICmpInst::Predicate SCC)
430{
431 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
432 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
433 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
434 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topper9d4171a2012-12-20 07:09:41 +0000435 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000436 ACst->getValue().isPowerOf2());
Craig Topper9d4171a2012-12-20 07:09:41 +0000437 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000438 BCst->getValue().isPowerOf2());
439 unsigned result = 0;
440 if (CCst != 0 && CCst->isZero()) {
441 // if C is zero, then both A and B qualify as mask
442 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
443 FoldMskICmp_Mask_AllZeroes |
444 FoldMskICmp_AMask_Mixed |
445 FoldMskICmp_BMask_Mixed)
446 : (FoldMskICmp_Mask_NotAllZeroes |
447 FoldMskICmp_Mask_NotAllZeroes |
448 FoldMskICmp_AMask_NotMixed |
449 FoldMskICmp_BMask_NotMixed));
450 if (icmp_abit)
451 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000452 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000453 : (FoldMskICmp_AMask_AllOnes |
454 FoldMskICmp_AMask_Mixed));
455 if (icmp_bbit)
456 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000457 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000458 : (FoldMskICmp_BMask_AllOnes |
459 FoldMskICmp_BMask_Mixed));
460 return result;
461 }
462 if (A == C) {
463 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
464 FoldMskICmp_AMask_Mixed)
465 : (FoldMskICmp_AMask_NotAllOnes |
466 FoldMskICmp_AMask_NotMixed));
467 if (icmp_abit)
468 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
469 FoldMskICmp_AMask_NotMixed)
470 : (FoldMskICmp_Mask_AllZeroes |
471 FoldMskICmp_AMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000472 } else if (ACst != 0 && CCst != 0 &&
473 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000474 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
475 : FoldMskICmp_AMask_NotMixed);
476 }
Craig Topperae48cb22012-12-20 07:15:54 +0000477 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000478 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
479 FoldMskICmp_BMask_Mixed)
480 : (FoldMskICmp_BMask_NotAllOnes |
481 FoldMskICmp_BMask_NotMixed));
482 if (icmp_bbit)
483 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000484 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000485 : (FoldMskICmp_Mask_AllZeroes |
486 FoldMskICmp_BMask_Mixed));
Craig Topperae48cb22012-12-20 07:15:54 +0000487 } else if (BCst != 0 && CCst != 0 &&
488 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000489 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
490 : FoldMskICmp_BMask_NotMixed);
491 }
492 return result;
493}
494
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000495/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
496/// if possible. The returned predicate is either == or !=. Returns false if
497/// decomposition fails.
498static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
499 Value *&X, Value *&Y, Value *&Z) {
500 // X < 0 is equivalent to (X & SignBit) != 0.
501 if (I->getPredicate() == ICmpInst::ICMP_SLT)
502 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
503 if (C->isZero()) {
504 X = I->getOperand(0);
505 Y = ConstantInt::get(I->getContext(),
506 APInt::getSignBit(C->getBitWidth()));
507 Pred = ICmpInst::ICMP_NE;
508 Z = C;
509 return true;
510 }
511
512 // X > -1 is equivalent to (X & SignBit) == 0.
513 if (I->getPredicate() == ICmpInst::ICMP_SGT)
514 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
515 if (C->isAllOnesValue()) {
516 X = I->getOperand(0);
517 Y = ConstantInt::get(I->getContext(),
518 APInt::getSignBit(C->getBitWidth()));
519 Pred = ICmpInst::ICMP_EQ;
520 Z = ConstantInt::getNullValue(C->getType());
521 return true;
522 }
523
524 return false;
525}
526
Owen Anderson3fe002d2010-09-08 22:16:17 +0000527/// foldLogOpOfMaskedICmpsHelper:
528/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
529/// return the set of pattern classes (from MaskedICmpType)
530/// that both LHS and RHS satisfy
Craig Topper9d4171a2012-12-20 07:09:41 +0000531static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000532 Value*& B, Value*& C,
533 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000534 ICmpInst *LHS, ICmpInst *RHS,
535 ICmpInst::Predicate &LHSCC,
536 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000537 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
538 // vectors are not (yet?) supported
539 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
540
541 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000542 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000543 // and L11 & L12 == L21 & L22. The same goes for RHS.
544 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000545 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000546 // above.
547 Value *L1 = LHS->getOperand(0);
548 Value *L2 = LHS->getOperand(1);
549 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000550 // Check whether the icmp can be decomposed into a bit test.
551 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
552 L21 = L22 = L1 = 0;
553 } else {
554 // Look for ANDs in the LHS icmp.
555 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
556 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
557 L21 = L22 = 0;
558 } else {
559 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
560 return 0;
561 std::swap(L1, L2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000562 L21 = L22 = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000563 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000565
566 // Bail if LHS was a icmp that can't be decomposed into an equality.
567 if (!ICmpInst::isEquality(LHSCC))
568 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000569
570 Value *R1 = RHS->getOperand(0);
571 Value *R2 = RHS->getOperand(1);
572 Value *R11,*R12;
573 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000574 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
575 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
576 A = R11; D = R12;
577 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
578 A = R12; D = R11;
579 } else {
580 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000581 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000582 E = R2; R1 = 0; ok = true;
583 } else if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
584 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
585 A = R11; D = R12; E = R2; ok = true;
586 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000587 A = R12; D = R11; E = R2; ok = true;
588 }
589 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000590
591 // Bail if RHS was a icmp that can't be decomposed into an equality.
592 if (!ICmpInst::isEquality(RHSCC))
593 return 0;
594
595 // Look for ANDs in on the right side of the RHS icmp.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000596 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000597 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
598 A = R11; D = R12; E = R1; ok = true;
599 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000600 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000601 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000602 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000603 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000604 }
605 if (!ok)
606 return 0;
607
608 if (L11 == A) {
609 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000610 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000611 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000612 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000613 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000614 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000615 B = L21; C = L1;
616 }
617
618 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
619 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
620 return left_type & right_type;
621}
622/// foldLogOpOfMaskedICmps:
623/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
624/// into a single (icmp(A & X) ==/!= Y)
625static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
626 ICmpInst::Predicate NEWCC,
627 llvm::InstCombiner::BuilderTy* Builder) {
628 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000629 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
630 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
631 LHSCC, RHSCC);
Benjamin Kramerf7fe24f2012-01-09 17:36:29 +0000632 if (mask == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000633 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
634 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000635
636 if (NEWCC == ICmpInst::ICMP_NE)
637 mask >>= 1; // treat "Not"-states as normal states
638
639 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000640 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000641 // -> (icmp eq (A & (B|D)), 0)
642 Value* newOr = Builder->CreateOr(B, D);
643 Value* newAnd = Builder->CreateAnd(A, newOr);
644 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000645 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000646 // with B and D, having a single bit set
647 Value* zero = Constant::getNullValue(A->getType());
648 return Builder->CreateICmp(NEWCC, newAnd, zero);
649 }
Craig Topperae48cb22012-12-20 07:15:54 +0000650 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000651 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000652 // -> (icmp eq (A & (B|D)), (B|D))
653 Value* newOr = Builder->CreateOr(B, D);
654 Value* newAnd = Builder->CreateAnd(A, newOr);
655 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000656 }
Craig Topperae48cb22012-12-20 07:15:54 +0000657 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000658 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000659 // -> (icmp eq (A & (B&D)), A)
660 Value* newAnd1 = Builder->CreateAnd(B, D);
661 Value* newAnd = Builder->CreateAnd(A, newAnd1);
662 return Builder->CreateICmp(NEWCC, newAnd, A);
663 }
Craig Topperae48cb22012-12-20 07:15:54 +0000664 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000665 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000666 // We already know that B & C == C && D & E == E.
667 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
668 // C and E, which are shared by both the mask B and the mask D, don't
669 // contradict, then we can transform to
670 // -> (icmp eq (A & (B|D)), (C|E))
671 // Currently, we only handle the case of B, C, D, and E being constant.
672 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
673 if (BCst == 0) return 0;
674 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
675 if (DCst == 0) return 0;
676 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000677 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000678 // with B and D, having a single bit set
679
680 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
681 if (CCst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000682 if (LHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000683 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
684 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
685 if (ECst == 0) return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000686 if (RHSCC != NEWCC)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000687 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
688 ConstantInt* MCst = dyn_cast<ConstantInt>(
689 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
690 ConstantExpr::getXor(CCst, ECst)) );
691 // if there is a conflict we should actually return a false for the
692 // whole construct
693 if (!MCst->isZero())
694 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000695 Value *newOr1 = Builder->CreateOr(B, D);
696 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
697 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000698 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
699 }
700 return 0;
701}
702
Chris Lattner0a8191e2010-01-05 07:50:36 +0000703/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000704Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000705 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
706
707 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
708 if (PredicatesFoldable(LHSCC, RHSCC)) {
709 if (LHS->getOperand(0) == RHS->getOperand(1) &&
710 LHS->getOperand(1) == RHS->getOperand(0))
711 LHS->swapOperands();
712 if (LHS->getOperand(0) == RHS->getOperand(0) &&
713 LHS->getOperand(1) == RHS->getOperand(1)) {
714 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
715 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
716 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000717 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000718 }
719 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000720
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000721 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
722 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
723 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000724
Chris Lattner0a8191e2010-01-05 07:50:36 +0000725 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
726 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
727 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
728 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
729 if (LHSCst == 0 || RHSCst == 0) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000730
Chris Lattner0a8191e2010-01-05 07:50:36 +0000731 if (LHSCst == RHSCst && LHSCC == RHSCC) {
732 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
733 // where C is a power of 2
734 if (LHSCC == ICmpInst::ICMP_ULT &&
735 LHSCst->getValue().isPowerOf2()) {
736 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000737 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000738 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000739
Chris Lattner0a8191e2010-01-05 07:50:36 +0000740 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
741 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
742 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000743 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000744 }
745 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000746
Benjamin Kramer101720f2011-04-28 20:09:57 +0000747 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000748 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000749 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000750 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000751 LHS->hasOneUse() && RHS->hasOneUse()) {
752 Value *V;
753 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
754
755 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000756 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000757 if (match(Val2, m_Trunc(m_Value(V))) &&
758 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
759 SmallCst = RHSCst;
760 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000761 } else if (match(Val, m_Trunc(m_Value(V))) &&
762 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000763 SmallCst = LHSCst;
764 BigCst = RHSCst;
765 }
766
767 if (SmallCst && BigCst) {
768 unsigned BigBitSize = BigCst->getType()->getBitWidth();
769 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
770
771 // Check that the low bits are zero.
772 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000773 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000774 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
775 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
776 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
777 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
778 }
779 }
780 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000781
Chris Lattner0a8191e2010-01-05 07:50:36 +0000782 // From here on, we only handle:
783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
784 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000785
Chris Lattner0a8191e2010-01-05 07:50:36 +0000786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
791 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000792
793 // Make a constant range that's the intersection of the two icmp ranges.
794 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000795 ConstantRange LHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000796 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000797 ConstantRange RHSRange =
Anders Carlssonda80afe2011-03-01 15:05:01 +0000798 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
799
800 if (LHSRange.intersectWith(RHSRange).isEmptySet())
801 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
802
Chris Lattner0a8191e2010-01-05 07:50:36 +0000803 // We can't fold (ugt x, C) & (sgt x, C2).
804 if (!PredicatesFoldable(LHSCC, RHSCC))
805 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +0000806
Chris Lattner0a8191e2010-01-05 07:50:36 +0000807 // Ensure that the larger constant is on the RHS.
808 bool ShouldSwap;
809 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000810 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000811 CmpInst::isSigned(RHSCC)))
812 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
813 else
814 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000815
Chris Lattner0a8191e2010-01-05 07:50:36 +0000816 if (ShouldSwap) {
817 std::swap(LHS, RHS);
818 std::swap(LHSCst, RHSCst);
819 std::swap(LHSCC, RHSCC);
820 }
821
Dan Gohman4a618822010-02-10 16:03:48 +0000822 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000823 // comparing a value against two constants and and'ing the result
824 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000825 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
826 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000827 // are not equal and that the larger constant is on the RHS
828 assert(LHSCst != RHSCst && "Compares not folded above?");
829
830 switch (LHSCC) {
831 default: llvm_unreachable("Unknown integer condition code!");
832 case ICmpInst::ICMP_EQ:
833 switch (RHSCC) {
834 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000835 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
836 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
837 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000838 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000839 }
840 case ICmpInst::ICMP_NE:
841 switch (RHSCC) {
842 default: llvm_unreachable("Unknown integer condition code!");
843 case ICmpInst::ICMP_ULT:
844 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000845 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000846 break; // (X != 13 & X u< 15) -> no change
847 case ICmpInst::ICMP_SLT:
848 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000849 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000850 break; // (X != 13 & X s< 15) -> no change
851 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
852 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
853 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000854 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000855 case ICmpInst::ICMP_NE:
856 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
857 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
858 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Chris Lattner067459c2010-03-05 08:46:26 +0000859 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000860 }
861 break; // (X != 13 & X != 15) -> no change
862 }
863 break;
864 case ICmpInst::ICMP_ULT:
865 switch (RHSCC) {
866 default: llvm_unreachable("Unknown integer condition code!");
867 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
868 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000869 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000870 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
871 break;
872 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
873 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000874 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000875 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
876 break;
877 }
878 break;
879 case ICmpInst::ICMP_SLT:
880 switch (RHSCC) {
881 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
883 break;
884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000886 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
888 break;
889 }
890 break;
891 case ICmpInst::ICMP_UGT:
892 switch (RHSCC) {
893 default: llvm_unreachable("Unknown integer condition code!");
894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000896 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
898 break;
899 case ICmpInst::ICMP_NE:
900 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000901 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000902 break; // (X u> 13 & X != 15) -> no change
903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000904 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000905 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
906 break;
907 }
908 break;
909 case ICmpInst::ICMP_SGT:
910 switch (RHSCC) {
911 default: llvm_unreachable("Unknown integer condition code!");
912 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
913 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000914 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
916 break;
917 case ICmpInst::ICMP_NE:
918 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000919 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000920 break; // (X s> 13 & X != 15) -> no change
921 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +0000922 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000923 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
924 break;
925 }
926 break;
927 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000928
Chris Lattner0a8191e2010-01-05 07:50:36 +0000929 return 0;
930}
931
Chris Lattner067459c2010-03-05 08:46:26 +0000932/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
933/// instcombine, this returns a Value which should already be inserted into the
934/// function.
935Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000936 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
937 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
938 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
939 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
940 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
941 // If either of the constants are nans, then the whole thing returns
942 // false.
943 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +0000944 return ConstantInt::getFalse(LHS->getContext());
945 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000946 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000947
Chris Lattner0a8191e2010-01-05 07:50:36 +0000948 // Handle vector zeros. This occurs because the canonical form of
949 // "fcmp ord x,x" is "fcmp ord x, 0".
950 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
951 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000952 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000953 return 0;
954 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000955
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
957 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
958 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +0000959
960
Chris Lattner0a8191e2010-01-05 07:50:36 +0000961 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
962 // Swap RHS operands to match LHS.
963 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
964 std::swap(Op1LHS, Op1RHS);
965 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000966
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
968 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
969 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +0000970 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000971 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +0000972 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000973 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000974 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000975 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000976 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +0000977
Chris Lattner0a8191e2010-01-05 07:50:36 +0000978 bool Op0Ordered;
979 bool Op1Ordered;
980 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
981 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +0000982 // uno && ord -> false
983 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
984 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000985 if (Op1Pred == 0) {
986 std::swap(LHS, RHS);
987 std::swap(Op0Pred, Op1Pred);
988 std::swap(Op0Ordered, Op1Ordered);
989 }
990 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +0000991 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +0000993 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
994 return LHS;
995 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +0000996 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +0000997
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +0000999 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001000 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001001 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001002 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001003 }
1004 }
1005
1006 return 0;
1007}
1008
1009
1010Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001011 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1013
1014 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1015 return ReplaceInstUsesWith(I, V);
1016
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001017 // (A|B)&(A|C) -> A|(B&C) etc
1018 if (Value *V = SimplifyUsingDistributiveLaws(I))
1019 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001020
Craig Topper9d4171a2012-12-20 07:09:41 +00001021 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 // purpose is to compute bits we don't care about.
1023 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001024 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001025
1026 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1027 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028
1029 // Optimize a variety of ((val OP C1) & C2) combinations...
1030 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1031 Value *Op0LHS = Op0I->getOperand(0);
1032 Value *Op0RHS = Op0I->getOperand(1);
1033 switch (Op0I->getOpcode()) {
1034 default: break;
1035 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001036 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001037 // If the mask is only needed on one incoming arm, push it up.
1038 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001039
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001040 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1042 // Not masking anything out for the LHS, move to RHS.
1043 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1044 Op0RHS->getName()+".masked");
1045 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1046 }
1047 if (!isa<Constant>(Op0RHS) &&
1048 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1049 // Not masking anything out for the RHS, move to LHS.
1050 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1051 Op0LHS->getName()+".masked");
1052 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1053 }
1054
1055 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001056 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001057 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001058 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1059 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1060 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001061 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1062 return BinaryOperator::CreateAnd(V, AndRHS);
1063 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1064 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1065 break;
1066
1067 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001068 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1069 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1070 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001071 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1072 return BinaryOperator::CreateAnd(V, AndRHS);
1073
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001074 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001075 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001076 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001077 uint32_t BitWidth = AndRHSMask.getBitWidth();
1078 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1079 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1080
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001081 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001082 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1083 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1084 }
1085 }
1086 break;
1087
1088 case Instruction::Shl:
1089 case Instruction::LShr:
1090 // (1 << x) & 1 --> zext(x == 0)
1091 // (1 >> x) & 1 --> zext(x == 0)
1092 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1093 Value *NewICmp =
1094 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1095 return new ZExtInst(NewICmp, I.getType());
1096 }
1097 break;
1098 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001099
Chris Lattner0a8191e2010-01-05 07:50:36 +00001100 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1101 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1102 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001103 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001104
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001105 // If this is an integer truncation, and if the source is an 'and' with
1106 // immediate, transform it. This frequently occurs for bitfield accesses.
1107 {
1108 Value *X = 0; ConstantInt *YC = 0;
1109 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1110 // Change: and (trunc (and X, YC) to T), C2
1111 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001112 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001113 // other simplifications.
1114 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1115 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1116 C3 = ConstantExpr::getAnd(C3, AndRHS);
1117 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001118 }
1119 }
1120
1121 // Try to fold constant and into select arguments.
1122 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123 if (Instruction *R = FoldOpIntoSelect(I, SI))
1124 return R;
1125 if (isa<PHINode>(Op0))
1126 if (Instruction *NV = FoldOpIntoPhi(I))
1127 return NV;
1128 }
1129
1130
1131 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1132 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1133 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1134 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1135 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1136 I.getName()+".demorgan");
1137 return BinaryOperator::CreateNot(Or);
1138 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001139
Chris Lattner0a8191e2010-01-05 07:50:36 +00001140 {
1141 Value *A = 0, *B = 0, *C = 0, *D = 0;
1142 // (A|B) & ~(A&B) -> A^B
1143 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1144 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1145 ((A == C && B == D) || (A == D && B == C)))
1146 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001147
Chris Lattner0a8191e2010-01-05 07:50:36 +00001148 // ~(A&B) & (A|B) -> A^B
1149 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1150 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1151 ((A == C && B == D) || (A == D && B == C)))
1152 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001153
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001154 // A&(A^B) => A & ~B
1155 {
1156 Value *tmpOp0 = Op0;
1157 Value *tmpOp1 = Op1;
1158 if (Op0->hasOneUse() &&
1159 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1160 if (A == Op1 || B == Op1 ) {
1161 tmpOp1 = Op0;
1162 tmpOp0 = Op1;
1163 // Simplify below
1164 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001166
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001167 if (tmpOp1->hasOneUse() &&
1168 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1169 if (B == tmpOp0) {
1170 std::swap(A, B);
1171 }
1172 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1173 // A is originally -1 (or a vector of -1 and undefs), then we enter
1174 // an endless loop. By checking that A is non-constant we ensure that
1175 // we will never get to the loop.
1176 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001177 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001178 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001179 }
1180
1181 // (A&((~A)|B)) -> A&B
1182 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1183 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1184 return BinaryOperator::CreateAnd(A, Op1);
1185 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1186 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1187 return BinaryOperator::CreateAnd(A, Op0);
1188 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001189
Chris Lattner0a8191e2010-01-05 07:50:36 +00001190 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1191 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001192 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1193 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001194
Chris Lattner4e8137d2010-02-11 06:26:33 +00001195 // If and'ing two fcmp, try combine them into one.
1196 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1197 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001198 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1199 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001200
1201
Chris Lattner0a8191e2010-01-05 07:50:36 +00001202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001205 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001206 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1207 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001208 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001209 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001210
Chris Lattner4e8137d2010-02-11 06:26:33 +00001211 // Only do this if the casts both really cause code to be generated.
1212 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1213 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1214 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001215 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1216 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001217
Chris Lattner4e8137d2010-02-11 06:26:33 +00001218 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1219 // cast is otherwise not optimizable. This happens for vector sexts.
1220 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1221 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001222 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001223 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001224
Chris Lattner4e8137d2010-02-11 06:26:33 +00001225 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1226 // cast is otherwise not optimizable. This happens for vector sexts.
1227 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1228 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001229 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001230 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001231 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001232 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001233
Chris Lattner0a8191e2010-01-05 07:50:36 +00001234 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1235 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1236 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001237 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001238 SI0->getOperand(1) == SI1->getOperand(1) &&
1239 (SI0->hasOneUse() || SI1->hasOneUse())) {
1240 Value *NewOp =
1241 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1242 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001243 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001244 SI1->getOperand(1));
1245 }
1246 }
1247
Chris Lattner0a8191e2010-01-05 07:50:36 +00001248 return Changed ? &I : 0;
1249}
1250
1251/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1252/// capable of providing pieces of a bswap. The subexpression provides pieces
1253/// of a bswap if it is proven that each of the non-zero bytes in the output of
1254/// the expression came from the corresponding "byte swapped" byte in some other
1255/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1256/// we know that the expression deposits the low byte of %X into the high byte
1257/// of the bswap result and that all other bytes are zero. This expression is
1258/// accepted, the high byte of ByteValues is set to X to indicate a correct
1259/// match.
1260///
1261/// This function returns true if the match was unsuccessful and false if so.
1262/// On entry to the function the "OverallLeftShift" is a signed integer value
1263/// indicating the number of bytes that the subexpression is later shifted. For
1264/// example, if the expression is later right shifted by 16 bits, the
1265/// OverallLeftShift value would be -2 on entry. This is used to specify which
1266/// byte of ByteValues is actually being set.
1267///
1268/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1269/// byte is masked to zero by a user. For example, in (X & 255), X will be
1270/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1271/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1272/// always in the local (OverallLeftShift) coordinate space.
1273///
1274static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1275 SmallVector<Value*, 8> &ByteValues) {
1276 if (Instruction *I = dyn_cast<Instruction>(V)) {
1277 // If this is an or instruction, it may be an inner node of the bswap.
1278 if (I->getOpcode() == Instruction::Or) {
1279 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1280 ByteValues) ||
1281 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1282 ByteValues);
1283 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001284
Chris Lattner0a8191e2010-01-05 07:50:36 +00001285 // If this is a logical shift by a constant multiple of 8, recurse with
1286 // OverallLeftShift and ByteMask adjusted.
1287 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001288 unsigned ShAmt =
Chris Lattner0a8191e2010-01-05 07:50:36 +00001289 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1290 // Ensure the shift amount is defined and of a byte value.
1291 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1292 return true;
1293
1294 unsigned ByteShift = ShAmt >> 3;
1295 if (I->getOpcode() == Instruction::Shl) {
1296 // X << 2 -> collect(X, +2)
1297 OverallLeftShift += ByteShift;
1298 ByteMask >>= ByteShift;
1299 } else {
1300 // X >>u 2 -> collect(X, -2)
1301 OverallLeftShift -= ByteShift;
1302 ByteMask <<= ByteShift;
1303 ByteMask &= (~0U >> (32-ByteValues.size()));
1304 }
1305
1306 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1307 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1308
Craig Topper9d4171a2012-12-20 07:09:41 +00001309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 ByteValues);
1311 }
1312
1313 // If this is a logical 'and' with a mask that clears bytes, clear the
1314 // corresponding bytes in ByteMask.
1315 if (I->getOpcode() == Instruction::And &&
1316 isa<ConstantInt>(I->getOperand(1))) {
1317 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1318 unsigned NumBytes = ByteValues.size();
1319 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1320 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001321
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1323 // If this byte is masked out by a later operation, we don't care what
1324 // the and mask is.
1325 if ((ByteMask & (1 << i)) == 0)
1326 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001327
Chris Lattner0a8191e2010-01-05 07:50:36 +00001328 // If the AndMask is all zeros for this byte, clear the bit.
1329 APInt MaskB = AndMask & Byte;
1330 if (MaskB == 0) {
1331 ByteMask &= ~(1U << i);
1332 continue;
1333 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001334
Chris Lattner0a8191e2010-01-05 07:50:36 +00001335 // If the AndMask is not all ones for this byte, it's not a bytezap.
1336 if (MaskB != Byte)
1337 return true;
1338
1339 // Otherwise, this byte is kept.
1340 }
1341
Craig Topper9d4171a2012-12-20 07:09:41 +00001342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001343 ByteValues);
1344 }
1345 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001346
Chris Lattner0a8191e2010-01-05 07:50:36 +00001347 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1348 // the input value to the bswap. Some observations: 1) if more than one byte
1349 // is demanded from this input, then it could not be successfully assembled
1350 // into a byteswap. At least one of the two bytes would not be aligned with
1351 // their ultimate destination.
1352 if (!isPowerOf2_32(ByteMask)) return true;
1353 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Craig Topper9d4171a2012-12-20 07:09:41 +00001354
Chris Lattner0a8191e2010-01-05 07:50:36 +00001355 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1356 // is demanded, it needs to go into byte 0 of the result. This means that the
1357 // byte needs to be shifted until it lands in the right byte bucket. The
1358 // shift amount depends on the position: if the byte is coming from the high
1359 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1360 // low part, it must be shifted left.
1361 unsigned DestByteNo = InputByteNo + OverallLeftShift;
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001362 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1363 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001364
Chris Lattner0a8191e2010-01-05 07:50:36 +00001365 // If the destination byte value is already defined, the values are or'd
1366 // together, which isn't a bswap (unless it's an or of the same bits).
1367 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1368 return true;
1369 ByteValues[DestByteNo] = V;
1370 return false;
1371}
1372
1373/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1374/// If so, insert the new bswap intrinsic and return it.
1375Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001376 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001377 if (!ITy || ITy->getBitWidth() % 16 ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00001378 // ByteMask only allows up to 32-byte values.
Craig Topper9d4171a2012-12-20 07:09:41 +00001379 ITy->getBitWidth() > 32*8)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001380 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Craig Topper9d4171a2012-12-20 07:09:41 +00001381
Chris Lattner0a8191e2010-01-05 07:50:36 +00001382 /// ByteValues - For each byte of the result, we keep track of which value
1383 /// defines each byte.
1384 SmallVector<Value*, 8> ByteValues;
1385 ByteValues.resize(ITy->getBitWidth()/8);
Craig Topper9d4171a2012-12-20 07:09:41 +00001386
Chris Lattner0a8191e2010-01-05 07:50:36 +00001387 // Try to find all the pieces corresponding to the bswap.
1388 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1389 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1390 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001391
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 // Check to see if all of the bytes come from the same value.
1393 Value *V = ByteValues[0];
1394 if (V == 0) return 0; // Didn't find a byte? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001395
Chris Lattner0a8191e2010-01-05 07:50:36 +00001396 // Check to make sure that all of the bytes come from the same value.
1397 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1398 if (ByteValues[i] != V)
1399 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001400 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001401 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001402 return CallInst::Create(F, V);
1403}
1404
1405/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1406/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1407/// we can simplify this expression to "cond ? C : D or B".
1408static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1409 Value *C, Value *D) {
1410 // If A is not a select of -1/0, this cannot match.
1411 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001412 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001413 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 return 0;
1415
1416 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001417 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001418 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001419 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001420 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001421
Chris Lattner0a8191e2010-01-05 07:50:36 +00001422 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001423 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001424 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001425 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001426 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001427 return 0;
1428}
1429
Chris Lattner067459c2010-03-05 08:46:26 +00001430/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1431Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001432 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1433
1434 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1435 if (PredicatesFoldable(LHSCC, RHSCC)) {
1436 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1437 LHS->getOperand(1) == RHS->getOperand(0))
1438 LHS->swapOperands();
1439 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1440 LHS->getOperand(1) == RHS->getOperand(1)) {
1441 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1442 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1443 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001444 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001445 }
1446 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001447
1448 // handle (roughly):
1449 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1450 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1451 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001452
Chris Lattner0a8191e2010-01-05 07:50:36 +00001453 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1454 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1455 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1456 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1457 if (LHSCst == 0 || RHSCst == 0) return 0;
1458
Owen Anderson8f306a72010-08-02 09:32:13 +00001459 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1460 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1461 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1462 Value *NewOr = Builder->CreateOr(Val, Val2);
1463 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1464 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001465 }
1466
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001467 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001468 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001469 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001470 ConstantInt *AddCst;
1471 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1472 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001473 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001474 }
1475
Chris Lattner0a8191e2010-01-05 07:50:36 +00001476 // From here on, we only handle:
1477 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1478 if (Val != Val2) return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001479
Chris Lattner0a8191e2010-01-05 07:50:36 +00001480 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1481 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1482 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1483 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1484 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1485 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001486
Chris Lattner0a8191e2010-01-05 07:50:36 +00001487 // We can't fold (ugt x, C) | (sgt x, C2).
1488 if (!PredicatesFoldable(LHSCC, RHSCC))
1489 return 0;
Craig Topper9d4171a2012-12-20 07:09:41 +00001490
Chris Lattner0a8191e2010-01-05 07:50:36 +00001491 // Ensure that the larger constant is on the RHS.
1492 bool ShouldSwap;
1493 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001494 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001495 CmpInst::isSigned(RHSCC)))
1496 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1497 else
1498 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001499
Chris Lattner0a8191e2010-01-05 07:50:36 +00001500 if (ShouldSwap) {
1501 std::swap(LHS, RHS);
1502 std::swap(LHSCst, RHSCst);
1503 std::swap(LHSCC, RHSCC);
1504 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001505
Dan Gohman4a618822010-02-10 16:03:48 +00001506 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001507 // comparing a value against two constants and or'ing the result
1508 // together. Because of the above check, we know that we only have
1509 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1510 // icmp folding check above), that the two constants are not
1511 // equal.
1512 assert(LHSCst != RHSCst && "Compares not folded above?");
1513
1514 switch (LHSCC) {
1515 default: llvm_unreachable("Unknown integer condition code!");
1516 case ICmpInst::ICMP_EQ:
1517 switch (RHSCC) {
1518 default: llvm_unreachable("Unknown integer condition code!");
1519 case ICmpInst::ICMP_EQ:
1520 if (LHSCst == SubOne(RHSCst)) {
1521 // (X == 13 | X == 14) -> X-13 <u 2
1522 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1523 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1524 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner067459c2010-03-05 08:46:26 +00001525 return Builder->CreateICmpULT(Add, AddCST);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001526 }
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001527
1528 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001529 // if LHSCst and RHSCst differ only by one bit:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001530 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001531 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1532
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001533 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1534 if (Xor.isPowerOf2()) {
1535 Value *NegCst = Builder->getInt(~Xor);
1536 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1537 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1538 }
1539 }
1540
Chris Lattner0a8191e2010-01-05 07:50:36 +00001541 break; // (X == 13 | X == 15) -> no change
1542 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1543 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1544 break;
1545 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1546 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1547 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001548 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001549 }
1550 break;
1551 case ICmpInst::ICMP_NE:
1552 switch (RHSCC) {
1553 default: llvm_unreachable("Unknown integer condition code!");
1554 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1555 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1556 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001557 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001558 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1559 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1560 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001561 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001562 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001563 case ICmpInst::ICMP_ULT:
1564 switch (RHSCC) {
1565 default: llvm_unreachable("Unknown integer condition code!");
1566 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1567 break;
1568 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1569 // If RHSCst is [us]MAXINT, it is always false. Not handling
1570 // this can cause overflow.
1571 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001572 return LHS;
1573 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001574 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1575 break;
1576 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1577 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001578 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001579 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1580 break;
1581 }
1582 break;
1583 case ICmpInst::ICMP_SLT:
1584 switch (RHSCC) {
1585 default: llvm_unreachable("Unknown integer condition code!");
1586 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1587 break;
1588 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1589 // If RHSCst is [us]MAXINT, it is always false. Not handling
1590 // this can cause overflow.
1591 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001592 return LHS;
1593 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001594 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1595 break;
1596 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1597 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001598 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001599 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1600 break;
1601 }
1602 break;
1603 case ICmpInst::ICMP_UGT:
1604 switch (RHSCC) {
1605 default: llvm_unreachable("Unknown integer condition code!");
1606 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1607 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001608 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001609 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1610 break;
1611 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1612 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001613 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001614 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1615 break;
1616 }
1617 break;
1618 case ICmpInst::ICMP_SGT:
1619 switch (RHSCC) {
1620 default: llvm_unreachable("Unknown integer condition code!");
1621 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1622 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001623 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001624 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1625 break;
1626 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1627 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001628 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001629 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1630 break;
1631 }
1632 break;
1633 }
1634 return 0;
1635}
1636
Chris Lattner067459c2010-03-05 08:46:26 +00001637/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1638/// instcombine, this returns a Value which should already be inserted into the
1639/// function.
1640Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001641 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001642 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001643 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1644 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1645 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1646 // If either of the constants are nans, then the whole thing returns
1647 // true.
1648 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +00001649 return ConstantInt::getTrue(LHS->getContext());
Craig Topper9d4171a2012-12-20 07:09:41 +00001650
Chris Lattner0a8191e2010-01-05 07:50:36 +00001651 // Otherwise, no need to compare the two constants, compare the
1652 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001653 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001654 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001655
Chris Lattner0a8191e2010-01-05 07:50:36 +00001656 // Handle vector zeros. This occurs because the canonical form of
1657 // "fcmp uno x,x" is "fcmp uno x, 0".
1658 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1659 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001660 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001661
Chris Lattner0a8191e2010-01-05 07:50:36 +00001662 return 0;
1663 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001664
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1666 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1667 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001668
Chris Lattner0a8191e2010-01-05 07:50:36 +00001669 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1670 // Swap RHS operands to match LHS.
1671 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1672 std::swap(Op1LHS, Op1RHS);
1673 }
1674 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1675 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1676 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001677 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001678 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001679 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001680 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001681 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001682 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001683 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001684 bool Op0Ordered;
1685 bool Op1Ordered;
1686 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1687 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1688 if (Op0Ordered == Op1Ordered) {
1689 // If both are ordered or unordered, return a new fcmp with
1690 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001691 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001692 }
1693 }
1694 return 0;
1695}
1696
1697/// FoldOrWithConstants - This helper function folds:
1698///
1699/// ((A | B) & C1) | (B & C2)
1700///
1701/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001702///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001703/// (A & C1) | B
1704///
1705/// when the XOR of the two constants is "all ones" (-1).
1706Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1707 Value *A, Value *B, Value *C) {
1708 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1709 if (!CI1) return 0;
1710
1711 Value *V1 = 0;
1712 ConstantInt *CI2 = 0;
1713 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1714
1715 APInt Xor = CI1->getValue() ^ CI2->getValue();
1716 if (!Xor.isAllOnesValue()) return 0;
1717
1718 if (V1 == A || V1 == B) {
1719 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1720 return BinaryOperator::CreateOr(NewOp, V1);
1721 }
1722
1723 return 0;
1724}
1725
1726Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001727 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1729
1730 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1731 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001732
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001733 // (A&B)|(A&C) -> A&(B|C) etc
1734 if (Value *V = SimplifyUsingDistributiveLaws(I))
1735 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001736
Craig Topper9d4171a2012-12-20 07:09:41 +00001737 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001738 // purpose is to compute bits we don't care about.
1739 if (SimplifyDemandedInstructionBits(I))
1740 return &I;
1741
1742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1743 ConstantInt *C1 = 0; Value *X = 0;
1744 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001745 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001746 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001747 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001748 Op0->hasOneUse()) {
1749 Value *Or = Builder->CreateOr(X, RHS);
1750 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001751 return BinaryOperator::CreateAnd(Or,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001752 ConstantInt::get(I.getContext(),
1753 RHS->getValue() | C1->getValue()));
1754 }
1755
1756 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1757 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1758 Op0->hasOneUse()) {
1759 Value *Or = Builder->CreateOr(X, RHS);
1760 Or->takeName(Op0);
1761 return BinaryOperator::CreateXor(Or,
1762 ConstantInt::get(I.getContext(),
1763 C1->getValue() & ~RHS->getValue()));
1764 }
1765
1766 // Try to fold constant and into select arguments.
1767 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1768 if (Instruction *R = FoldOpIntoSelect(I, SI))
1769 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001770
Chris Lattner0a8191e2010-01-05 07:50:36 +00001771 if (isa<PHINode>(Op0))
1772 if (Instruction *NV = FoldOpIntoPhi(I))
1773 return NV;
1774 }
1775
1776 Value *A = 0, *B = 0;
1777 ConstantInt *C1 = 0, *C2 = 0;
1778
1779 // (A | B) | C and A | (B | C) -> bswap if possible.
1780 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1781 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1782 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001783 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1784 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001785 if (Instruction *BSwap = MatchBSwap(I))
1786 return BSwap;
1787 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001788
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001789 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 if (Op0->hasOneUse() &&
1791 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1792 MaskedValueIsZero(Op1, C1->getValue())) {
1793 Value *NOr = Builder->CreateOr(A, Op1);
1794 NOr->takeName(Op0);
1795 return BinaryOperator::CreateXor(NOr, C1);
1796 }
1797
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001798 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 if (Op1->hasOneUse() &&
1800 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1801 MaskedValueIsZero(Op0, C1->getValue())) {
1802 Value *NOr = Builder->CreateOr(A, Op0);
1803 NOr->takeName(Op0);
1804 return BinaryOperator::CreateXor(NOr, C1);
1805 }
1806
1807 // (A & C)|(B & D)
1808 Value *C = 0, *D = 0;
1809 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1810 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001811 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001812 C1 = dyn_cast<ConstantInt>(C);
1813 C2 = dyn_cast<ConstantInt>(D);
1814 if (C1 && C2) { // (A & C1)|(B & C2)
1815 // If we have: ((V + N) & C1) | (V & C2)
1816 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1817 // replace with V+N.
1818 if (C1->getValue() == ~C2->getValue()) {
1819 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1820 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1821 // Add commutes, try both ways.
1822 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1823 return ReplaceInstUsesWith(I, A);
1824 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1825 return ReplaceInstUsesWith(I, A);
1826 }
1827 // Or commutes, try both ways.
1828 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1829 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1830 // Add commutes, try both ways.
1831 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1832 return ReplaceInstUsesWith(I, B);
1833 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1834 return ReplaceInstUsesWith(I, B);
1835 }
1836 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001837
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00001839 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001840 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001841 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1842 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1843 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1844 return BinaryOperator::CreateAnd(A,
1845 ConstantInt::get(A->getContext(),
1846 C1->getValue()|C2->getValue()));
1847 // Or commutes, try both ways.
1848 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1849 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1850 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1851 return BinaryOperator::CreateAnd(B,
1852 ConstantInt::get(B->getContext(),
1853 C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001854
Chris Lattner95188692010-01-11 06:55:24 +00001855 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001856 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Chris Lattner95188692010-01-11 06:55:24 +00001857 ConstantInt *C3 = 0, *C4 = 0;
1858 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1859 (C3->getValue() & ~C1->getValue()) == 0 &&
1860 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1861 (C4->getValue() & ~C2->getValue()) == 0) {
1862 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1863 return BinaryOperator::CreateAnd(V2,
1864 ConstantInt::get(B->getContext(),
1865 C1->getValue()|C2->getValue()));
1866 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001867 }
1868 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001869
Chris Lattner8e2c4712010-02-02 02:43:51 +00001870 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1871 // Don't do this for vector select idioms, the code generator doesn't handle
1872 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00001873 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00001874 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1875 return Match;
1876 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1877 return Match;
1878 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1879 return Match;
1880 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1881 return Match;
1882 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883
1884 // ((A&~B)|(~A&B)) -> A^B
1885 if ((match(C, m_Not(m_Specific(D))) &&
1886 match(B, m_Not(m_Specific(A)))))
1887 return BinaryOperator::CreateXor(A, D);
1888 // ((~B&A)|(~A&B)) -> A^B
1889 if ((match(A, m_Not(m_Specific(D))) &&
1890 match(B, m_Not(m_Specific(C)))))
1891 return BinaryOperator::CreateXor(C, D);
1892 // ((A&~B)|(B&~A)) -> A^B
1893 if ((match(C, m_Not(m_Specific(B))) &&
1894 match(D, m_Not(m_Specific(A)))))
1895 return BinaryOperator::CreateXor(A, B);
1896 // ((~B&A)|(B&~A)) -> A^B
1897 if ((match(A, m_Not(m_Specific(B))) &&
1898 match(D, m_Not(m_Specific(C)))))
1899 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00001900
1901 // ((A|B)&1)|(B&-2) -> (A&1) | B
1902 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1903 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1904 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1905 if (Ret) return Ret;
1906 }
1907 // (B&-2)|((A|B)&1) -> (A&1) | B
1908 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1909 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1910 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1911 if (Ret) return Ret;
1912 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001913 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001914
Chris Lattner0a8191e2010-01-05 07:50:36 +00001915 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1916 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1917 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
Craig Topper9d4171a2012-12-20 07:09:41 +00001918 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001919 SI0->getOperand(1) == SI1->getOperand(1) &&
1920 (SI0->hasOneUse() || SI1->hasOneUse())) {
1921 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1922 SI0->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00001923 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00001924 SI1->getOperand(1));
1925 }
1926 }
1927
Chris Lattner0a8191e2010-01-05 07:50:36 +00001928 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1929 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1930 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1931 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1932 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1933 I.getName()+".demorgan");
1934 return BinaryOperator::CreateNot(And);
1935 }
1936
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001937 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00001938 bool SwappedForXor = false;
1939 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001940 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00001941 SwappedForXor = true;
1942 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001943
1944 // A | ( A ^ B) -> A | B
1945 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00001946 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001947 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1948 if (Op0 == A || Op0 == B)
1949 return BinaryOperator::CreateOr(A, B);
1950
Chad Rosier7813dce2012-04-26 23:29:14 +00001951 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1952 match(Op0, m_And(m_Specific(B), m_Specific(A))))
1953 return BinaryOperator::CreateOr(A, B);
1954
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001955 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1956 Value *Not = Builder->CreateNot(B, B->getName()+".not");
1957 return BinaryOperator::CreateOr(Not, Op0);
1958 }
1959 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1960 Value *Not = Builder->CreateNot(A, A->getName()+".not");
1961 return BinaryOperator::CreateOr(Not, Op0);
1962 }
1963 }
1964
1965 // A | ~(A | B) -> A | ~B
1966 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001967 if (match(Op1, m_Not(m_Value(A))))
1968 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001969 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1970 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1971 B->getOpcode() == Instruction::Xor)) {
1972 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1973 B->getOperand(0);
1974 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1975 return BinaryOperator::CreateOr(Not, Op0);
1976 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001977
Eli Friedmane06535b2012-03-16 00:52:42 +00001978 if (SwappedForXor)
1979 std::swap(Op0, Op1);
1980
Chris Lattner0a8191e2010-01-05 07:50:36 +00001981 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1982 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00001983 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1984 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001985
Chris Lattner4e8137d2010-02-11 06:26:33 +00001986 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1987 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1988 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001989 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1990 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001991
Chris Lattner0a8191e2010-01-05 07:50:36 +00001992 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1993 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00001994 CastInst *Op1C = dyn_cast<CastInst>(Op1);
1995 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00001996 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00001997 if (SrcTy == Op1C->getOperand(0)->getType() &&
1998 SrcTy->isIntOrIntVectorTy()) {
1999 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002000
Chris Lattner311aa632011-01-15 05:40:29 +00002001 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2002 // Only do this if the casts both really cause code to be
2003 // generated.
2004 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2005 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2006 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2007 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002008 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002009
Chris Lattner311aa632011-01-15 05:40:29 +00002010 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2011 // cast is otherwise not optimizable. This happens for vector sexts.
2012 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2013 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2014 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2015 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002016
Chris Lattner311aa632011-01-15 05:40:29 +00002017 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2018 // cast is otherwise not optimizable. This happens for vector sexts.
2019 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2020 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2021 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2022 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023 }
Chris Lattner311aa632011-01-15 05:40:29 +00002024 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025 }
Eli Friedman23956262011-04-14 22:41:27 +00002026
2027 // or(sext(A), B) -> A ? -1 : B where A is an i1
2028 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2029 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2030 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2031 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2032 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2033
Owen Andersonc237a842010-09-13 17:59:27 +00002034 // Note: If we've gotten to the point of visiting the outer OR, then the
2035 // inner one couldn't be simplified. If it was a constant, then it won't
2036 // be simplified by a later pass either, so we try swapping the inner/outer
2037 // ORs in the hopes that we'll be able to simplify it this way.
2038 // (X|C) | V --> (X|V) | C
2039 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2040 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2041 Value *Inner = Builder->CreateOr(A, Op1);
2042 Inner->takeName(Op0);
2043 return BinaryOperator::CreateOr(Inner, C1);
2044 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002045
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 return Changed ? &I : 0;
2047}
2048
2049Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002050 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2052
Duncan Sandsc89ac072010-11-17 18:52:15 +00002053 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2054 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002055
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002056 // (A&B)^(A&C) -> A&(B^C) etc
2057 if (Value *V = SimplifyUsingDistributiveLaws(I))
2058 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002059
Craig Topper9d4171a2012-12-20 07:09:41 +00002060 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002061 // purpose is to compute bits we don't care about.
2062 if (SimplifyDemandedInstructionBits(I))
2063 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002064
2065 // Is this a ~ operation?
2066 if (Value *NotOp = dyn_castNotVal(&I)) {
2067 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002068 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002069 Op0I->getOpcode() == Instruction::Or) {
2070 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2071 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2072 if (dyn_castNotVal(Op0I->getOperand(1)))
2073 Op0I->swapOperands();
2074 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2075 Value *NotY =
2076 Builder->CreateNot(Op0I->getOperand(1),
2077 Op0I->getOperand(1)->getName()+".not");
2078 if (Op0I->getOpcode() == Instruction::And)
2079 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2080 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2081 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002082
Chris Lattner0a8191e2010-01-05 07:50:36 +00002083 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2084 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Craig Topper9d4171a2012-12-20 07:09:41 +00002085 if (isFreeToInvert(Op0I->getOperand(0)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 isFreeToInvert(Op0I->getOperand(1))) {
2087 Value *NotX =
2088 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2089 Value *NotY =
2090 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2091 if (Op0I->getOpcode() == Instruction::And)
2092 return BinaryOperator::CreateOr(NotX, NotY);
2093 return BinaryOperator::CreateAnd(NotX, NotY);
2094 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002095
2096 } else if (Op0I->getOpcode() == Instruction::AShr) {
2097 // ~(~X >>s Y) --> (X >>s Y)
2098 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2099 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002100 }
2101 }
2102 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002103
2104
Chris Lattner0a8191e2010-01-05 07:50:36 +00002105 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002106 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002108 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2109 return CmpInst::Create(CI->getOpcode(),
2110 CI->getInversePredicate(),
2111 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002112
2113 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2114 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2115 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2116 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2117 Instruction::CastOps Opcode = Op0C->getOpcode();
2118 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002119 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002120 ConstantInt::getTrue(I.getContext()),
2121 Op0C->getDestTy()))) {
2122 CI->setPredicate(CI->getInversePredicate());
2123 return CastInst::Create(Opcode, CI, Op0C->getType());
2124 }
2125 }
2126 }
2127 }
2128
2129 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2130 // ~(c-X) == X-c-1 == X+(-c-1)
2131 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2132 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2133 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2134 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2135 ConstantInt::get(I.getType(), 1));
2136 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2137 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002138
Chris Lattner0a8191e2010-01-05 07:50:36 +00002139 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2140 if (Op0I->getOpcode() == Instruction::Add) {
2141 // ~(X-c) --> (-c-1)-X
2142 if (RHS->isAllOnesValue()) {
2143 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2144 return BinaryOperator::CreateSub(
2145 ConstantExpr::getSub(NegOp0CI,
2146 ConstantInt::get(I.getType(), 1)),
2147 Op0I->getOperand(0));
2148 } else if (RHS->getValue().isSignBit()) {
2149 // (X + C) ^ signbit -> (X + C + signbit)
2150 Constant *C = ConstantInt::get(I.getContext(),
2151 RHS->getValue() + Op0CI->getValue());
2152 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2153
2154 }
2155 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002156 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002157 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2158 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2159 // Anything in both C1 and C2 is known to be zero, remove it from
2160 // NewRHS.
2161 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002162 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002163 ConstantExpr::getNot(CommonBits));
2164 Worklist.Add(Op0I);
2165 I.setOperand(0, Op0I->getOperand(0));
2166 I.setOperand(1, NewRHS);
2167 return &I;
2168 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002169 } else if (Op0I->getOpcode() == Instruction::LShr) {
2170 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2171 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002172 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002173 ConstantInt *C1;
2174 if (Op0I->hasOneUse() &&
2175 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2176 E1->getOpcode() == Instruction::Xor &&
2177 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2178 // fold (C1 >> C2) ^ C3
2179 ConstantInt *C2 = Op0CI, *C3 = RHS;
2180 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2181 FoldConst ^= C3->getValue();
2182 // Prepare the two operands.
2183 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2184 Opnd0->takeName(Op0I);
2185 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2186 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2187
2188 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2189 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002190 }
2191 }
2192 }
2193
2194 // Try to fold constant and into select arguments.
2195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2196 if (Instruction *R = FoldOpIntoSelect(I, SI))
2197 return R;
2198 if (isa<PHINode>(Op0))
2199 if (Instruction *NV = FoldOpIntoPhi(I))
2200 return NV;
2201 }
2202
Chris Lattner0a8191e2010-01-05 07:50:36 +00002203 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2204 if (Op1I) {
2205 Value *A, *B;
2206 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2207 if (A == Op0) { // B^(B|A) == (A|B)^B
2208 Op1I->swapOperands();
2209 I.swapOperands();
2210 std::swap(Op0, Op1);
2211 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2212 I.swapOperands(); // Simplified below.
2213 std::swap(Op0, Op1);
2214 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002215 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002216 Op1I->hasOneUse()){
2217 if (A == Op0) { // A^(A&B) -> A^(B&A)
2218 Op1I->swapOperands();
2219 std::swap(A, B);
2220 }
2221 if (B == Op0) { // A^(B&A) -> (B&A)^A
2222 I.swapOperands(); // Simplified below.
2223 std::swap(Op0, Op1);
2224 }
2225 }
2226 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002227
Chris Lattner0a8191e2010-01-05 07:50:36 +00002228 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2229 if (Op0I) {
2230 Value *A, *B;
2231 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2232 Op0I->hasOneUse()) {
2233 if (A == Op1) // (B|A)^B == (A|B)^B
2234 std::swap(A, B);
2235 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002236 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002237 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002238 Op0I->hasOneUse()){
2239 if (A == Op1) // (A&B)^A -> (B&A)^A
2240 std::swap(A, B);
2241 if (B == Op1 && // (B&A)^A == ~B & A
2242 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002243 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002244 }
2245 }
2246 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002247
Chris Lattner0a8191e2010-01-05 07:50:36 +00002248 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Craig Topper9d4171a2012-12-20 07:09:41 +00002249 if (Op0I && Op1I && Op0I->isShift() &&
2250 Op0I->getOpcode() == Op1I->getOpcode() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002251 Op0I->getOperand(1) == Op1I->getOperand(1) &&
Benjamin Kramer9d5849f2012-05-28 20:52:48 +00002252 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002253 Value *NewOp =
2254 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2255 Op0I->getName());
Craig Topper9d4171a2012-12-20 07:09:41 +00002256 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002257 Op1I->getOperand(1));
2258 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002259
Chris Lattner0a8191e2010-01-05 07:50:36 +00002260 if (Op0I && Op1I) {
2261 Value *A, *B, *C, *D;
2262 // (A & B)^(A | B) -> A ^ B
2263 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2264 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002265 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002266 return BinaryOperator::CreateXor(A, B);
2267 }
2268 // (A | B)^(A & B) -> A ^ B
2269 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2270 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002271 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002272 return BinaryOperator::CreateXor(A, B);
2273 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002274 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002275
Chris Lattner0a8191e2010-01-05 07:50:36 +00002276 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2277 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2278 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2279 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2280 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2281 LHS->getOperand(1) == RHS->getOperand(0))
2282 LHS->swapOperands();
2283 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2284 LHS->getOperand(1) == RHS->getOperand(1)) {
2285 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2286 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2287 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002288 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002289 getNewICmpValue(isSigned, Code, Op0, Op1,
2290 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002291 }
2292 }
2293
2294 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2295 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2296 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2297 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002298 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002299 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002300 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002301 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002302 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002303 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002304 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002305 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2306 Op1C->getOperand(0), I.getName());
2307 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2308 }
2309 }
2310 }
2311
2312 return Changed ? &I : 0;
2313}