blob: 96ca40a3cf95db5dbf263ae96f70250251304783 [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"
15#include "llvm/Intrinsics.h"
16#include "llvm/Analysis/InstructionSimplify.h"
Pete Cooperebf98c12011-12-17 01:20:32 +000017#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
Anders Carlssonda80afe2011-03-01 15:05:01 +000018#include "llvm/Support/ConstantRange.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000019#include "llvm/Support/PatternMatch.h"
20using 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;
39
40 // Constants can be considered to be not'ed values.
41 if (isa<ConstantInt>(V))
42 return true;
43
44 // Compares can be inverted if they have a single use.
45 if (CmpInst *CI = dyn_cast<CmpInst>(V))
46 return CI->hasOneUse();
47
48 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 }
59
60 // 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!");
90 return 0;
91 }
92}
93
94/// getICmpValue - This is the complement of getICmpCode, which turns an
95/// opcode and two operands into either a constant true or false, or a brand
96/// new ICmp instruction. The sign is passed in to determine which kind
97/// of predicate to use in the new icmp instruction.
Pete Cooperebf98c12011-12-17 01:20:32 +000098Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
99 InstCombiner::BuilderTy *Builder) {
100 ICmpInst::Predicate NewPred;
101 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
102 return NewConstant;
103 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000104}
105
106/// getFCmpValue - This is the complement of getFCmpCode, which turns an
107/// opcode and two operands into either a FCmp instruction. isordered is passed
108/// in to determine which kind of predicate to use in the new fcmp instruction.
109static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000110 Value *LHS, Value *RHS,
111 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000112 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000113 switch (code) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000114 default: assert(0 && "Illegal FCmp code!");
115 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
116 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
117 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
118 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
119 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
120 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
121 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Owen Andersona8342002011-01-21 19:39:42 +0000122 case 7:
123 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
124 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000125 }
Chris Lattner067459c2010-03-05 08:46:26 +0000126 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000127}
128
Chris Lattner0a8191e2010-01-05 07:50:36 +0000129// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
130// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
131// guaranteed to be a binary operator.
132Instruction *InstCombiner::OptAndOp(Instruction *Op,
133 ConstantInt *OpRHS,
134 ConstantInt *AndRHS,
135 BinaryOperator &TheAnd) {
136 Value *X = Op->getOperand(0);
137 Constant *Together = 0;
138 if (!Op->isShift())
139 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
140
141 switch (Op->getOpcode()) {
142 case Instruction::Xor:
143 if (Op->hasOneUse()) {
144 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
145 Value *And = Builder->CreateAnd(X, AndRHS);
146 And->takeName(Op);
147 return BinaryOperator::CreateXor(And, Together);
148 }
149 break;
150 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000151 if (Op->hasOneUse()){
152 if (Together != OpRHS) {
153 // (X | C1) & C2 --> (X | (C1&C2)) & C2
154 Value *Or = Builder->CreateOr(X, Together);
155 Or->takeName(Op);
156 return BinaryOperator::CreateAnd(Or, AndRHS);
157 }
158
159 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
160 if (TogetherCI && !TogetherCI->isZero()){
161 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
162 // NOTE: This reduces the number of bits set in the & mask, which
163 // can expose opportunities for store narrowing.
164 Together = ConstantExpr::getXor(AndRHS, Together);
165 Value *And = Builder->CreateAnd(X, Together);
166 And->takeName(Op);
167 return BinaryOperator::CreateOr(And, OpRHS);
168 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000169 }
Owen Andersonc237a842010-09-13 17:59:27 +0000170
Chris Lattner0a8191e2010-01-05 07:50:36 +0000171 break;
172 case Instruction::Add:
173 if (Op->hasOneUse()) {
174 // Adding a one to a single bit bit-field should be turned into an XOR
175 // of the bit. First thing to check is to see if this AND is with a
176 // single bit constant.
177 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
178
179 // If there is only one bit set.
180 if (AndRHSV.isPowerOf2()) {
181 // Ok, at this point, we know that we are masking the result of the
182 // ADD down to exactly one bit. If the constant we are adding has
183 // no bits set below this bit, then we can eliminate the ADD.
184 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
185
186 // Check to see if any bits below the one bit set in AndRHSV are set.
187 if ((AddRHS & (AndRHSV-1)) == 0) {
188 // If not, the only thing that can effect the output of the AND is
189 // the bit specified by AndRHSV. If that bit is set, the effect of
190 // the XOR is to toggle the bit. If it is clear, then the ADD has
191 // no effect.
192 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
193 TheAnd.setOperand(0, X);
194 return &TheAnd;
195 } else {
196 // Pull the XOR out of the AND.
197 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
198 NewAnd->takeName(Op);
199 return BinaryOperator::CreateXor(NewAnd, AndRHS);
200 }
201 }
202 }
203 }
204 break;
205
206 case Instruction::Shl: {
207 // We know that the AND will not produce any of the bits shifted in, so if
208 // the anded constant includes them, clear them now!
209 //
210 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
211 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
212 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
213 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
214 AndRHS->getValue() & ShlMask);
215
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000216 if (CI->getValue() == ShlMask)
217 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000218 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000219
220 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000221 TheAnd.setOperand(1, CI);
222 return &TheAnd;
223 }
224 break;
225 }
226 case Instruction::LShr: {
227 // We know that the AND will not produce any of the bits shifted in, so if
228 // the anded constant includes them, clear them now! This only applies to
229 // unsigned shifts, because a signed shr may bring in set bits!
230 //
231 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
232 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
233 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
234 ConstantInt *CI = ConstantInt::get(Op->getContext(),
235 AndRHS->getValue() & ShrMask);
236
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000237 if (CI->getValue() == ShrMask)
238 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000239 return ReplaceInstUsesWith(TheAnd, Op);
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000240
241 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000242 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
243 return &TheAnd;
244 }
245 break;
246 }
247 case Instruction::AShr:
248 // Signed shr.
249 // See if this is shifting in some sign extension, then masking it out
250 // with an and.
251 if (Op->hasOneUse()) {
252 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
253 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
254 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
255 Constant *C = ConstantInt::get(Op->getContext(),
256 AndRHS->getValue() & ShrMask);
257 if (C == AndRHS) { // Masking out bits shifted in.
258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
259 // Make the argument unsigned.
260 Value *ShVal = Op->getOperand(0);
261 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
262 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
263 }
264 }
265 break;
266 }
267 return 0;
268}
269
270
271/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000272/// true, otherwise (V < Lo || V >= Hi). In practice, we emit the more efficient
Chris Lattner0a8191e2010-01-05 07:50:36 +0000273/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
274/// whether to treat the V, Lo and HI as signed or not. IB is the location to
275/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000276Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
277 bool isSigned, bool Inside) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000278 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
279 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
280 "Lo is not <= Hi in range emission code!");
281
282 if (Inside) {
283 if (Lo == Hi) // Trivially false.
Chris Lattner067459c2010-03-05 08:46:26 +0000284 return ConstantInt::getFalse(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000285
286 // V >= Min && V < Hi --> V < Hi
287 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
288 ICmpInst::Predicate pred = (isSigned ?
289 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000290 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000291 }
292
293 // Emit V-Lo <u Hi-Lo
294 Constant *NegLo = ConstantExpr::getNeg(Lo);
295 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
296 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000297 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000298 }
299
300 if (Lo == Hi) // Trivially true.
Chris Lattner067459c2010-03-05 08:46:26 +0000301 return ConstantInt::getTrue(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000302
303 // V < Min || V >= Hi -> V > Hi-1
304 Hi = SubOne(cast<ConstantInt>(Hi));
305 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
306 ICmpInst::Predicate pred = (isSigned ?
307 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000308 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000309 }
310
311 // Emit V-Lo >u Hi-1-Lo
312 // Note that Hi has already had one subtracted from it, above.
313 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
314 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
315 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000316 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000317}
318
319// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
320// any number of 0s on either side. The 1s are allowed to wrap from LSB to
321// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
322// not, since all 1s are not contiguous.
323static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
324 const APInt& V = Val->getValue();
325 uint32_t BitWidth = Val->getType()->getBitWidth();
326 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
327
328 // look for the first zero bit after the run of ones
329 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
330 // look for the first non-zero bit
331 ME = V.getActiveBits();
332 return true;
333}
334
335/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
336/// where isSub determines whether the operator is a sub. If we can fold one of
337/// the following xforms:
338///
339/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
340/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
341/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
342///
343/// return (A +/- B).
344///
345Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
346 ConstantInt *Mask, bool isSub,
347 Instruction &I) {
348 Instruction *LHSI = dyn_cast<Instruction>(LHS);
349 if (!LHSI || LHSI->getNumOperands() != 2 ||
350 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
351
352 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
353
354 switch (LHSI->getOpcode()) {
355 default: return 0;
356 case Instruction::And:
357 if (ConstantExpr::getAnd(N, Mask) == Mask) {
358 // If the AndRHS is a power of two minus one (0+1+), this is simple.
359 if ((Mask->getValue().countLeadingZeros() +
360 Mask->getValue().countPopulation()) ==
361 Mask->getValue().getBitWidth())
362 break;
363
364 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
365 // part, we don't need any explicit masks to take them out of A. If that
366 // is all N is, ignore it.
367 uint32_t MB = 0, ME = 0;
368 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
369 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
370 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
371 if (MaskedValueIsZero(RHS, Mask))
372 break;
373 }
374 }
375 return 0;
376 case Instruction::Or:
377 case Instruction::Xor:
378 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
379 if ((Mask->getValue().countLeadingZeros() +
380 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
381 && ConstantExpr::getAnd(N, Mask)->isNullValue())
382 break;
383 return 0;
384 }
385
386 if (isSub)
387 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
388 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
389}
390
Owen Anderson3fe002d2010-09-08 22:16:17 +0000391/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
392/// One of A and B is considered the mask, the other the value. This is
393/// described as the "AMask" or "BMask" part of the enum. If the enum
394/// contains only "Mask", then both A and B can be considered masks.
395/// If A is the mask, then it was proven, that (A & C) == C. This
396/// is trivial if C == A, or C == 0. If both A and C are constants, this
397/// proof is also easy.
398/// For the following explanations we assume that A is the mask.
399/// The part "AllOnes" declares, that the comparison is true only
400/// if (A & B) == A, or all bits of A are set in B.
401/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
402/// The part "AllZeroes" declares, that the comparison is true only
403/// if (A & B) == 0, or all bits of A are cleared in B.
404/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
405/// The part "Mixed" declares, that (A & B) == C and C might or might not
406/// contain any number of one bits and zero bits.
407/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
408/// The Part "Not" means, that in above descriptions "==" should be replaced
409/// by "!=".
410/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
411/// If the mask A contains a single bit, then the following is equivalent:
412/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
413/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
414enum MaskedICmpType {
415 FoldMskICmp_AMask_AllOnes = 1,
416 FoldMskICmp_AMask_NotAllOnes = 2,
417 FoldMskICmp_BMask_AllOnes = 4,
418 FoldMskICmp_BMask_NotAllOnes = 8,
419 FoldMskICmp_Mask_AllZeroes = 16,
420 FoldMskICmp_Mask_NotAllZeroes = 32,
421 FoldMskICmp_AMask_Mixed = 64,
422 FoldMskICmp_AMask_NotMixed = 128,
423 FoldMskICmp_BMask_Mixed = 256,
424 FoldMskICmp_BMask_NotMixed = 512
425};
426
427/// return the set of pattern classes (from MaskedICmpType)
428/// that (icmp SCC (A & B), C) satisfies
429static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
430 ICmpInst::Predicate SCC)
431{
432 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
433 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
434 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
435 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
436 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
437 ACst->getValue().isPowerOf2());
438 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
439 BCst->getValue().isPowerOf2());
440 unsigned result = 0;
441 if (CCst != 0 && CCst->isZero()) {
442 // if C is zero, then both A and B qualify as mask
443 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
444 FoldMskICmp_Mask_AllZeroes |
445 FoldMskICmp_AMask_Mixed |
446 FoldMskICmp_BMask_Mixed)
447 : (FoldMskICmp_Mask_NotAllZeroes |
448 FoldMskICmp_Mask_NotAllZeroes |
449 FoldMskICmp_AMask_NotMixed |
450 FoldMskICmp_BMask_NotMixed));
451 if (icmp_abit)
452 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
453 FoldMskICmp_AMask_NotMixed)
454 : (FoldMskICmp_AMask_AllOnes |
455 FoldMskICmp_AMask_Mixed));
456 if (icmp_bbit)
457 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
458 FoldMskICmp_BMask_NotMixed)
459 : (FoldMskICmp_BMask_AllOnes |
460 FoldMskICmp_BMask_Mixed));
461 return result;
462 }
463 if (A == C) {
464 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
465 FoldMskICmp_AMask_Mixed)
466 : (FoldMskICmp_AMask_NotAllOnes |
467 FoldMskICmp_AMask_NotMixed));
468 if (icmp_abit)
469 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
470 FoldMskICmp_AMask_NotMixed)
471 : (FoldMskICmp_Mask_AllZeroes |
472 FoldMskICmp_AMask_Mixed));
473 }
474 else if (ACst != 0 && CCst != 0 &&
475 ConstantExpr::getAnd(ACst, CCst) == CCst) {
476 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
477 : FoldMskICmp_AMask_NotMixed);
478 }
479 if (B == C)
480 {
481 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
482 FoldMskICmp_BMask_Mixed)
483 : (FoldMskICmp_BMask_NotAllOnes |
484 FoldMskICmp_BMask_NotMixed));
485 if (icmp_bbit)
486 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
487 FoldMskICmp_BMask_NotMixed)
488 : (FoldMskICmp_Mask_AllZeroes |
489 FoldMskICmp_BMask_Mixed));
490 }
491 else if (BCst != 0 && CCst != 0 &&
492 ConstantExpr::getAnd(BCst, CCst) == CCst) {
493 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
494 : FoldMskICmp_BMask_NotMixed);
495 }
496 return result;
497}
498
499/// foldLogOpOfMaskedICmpsHelper:
500/// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
501/// return the set of pattern classes (from MaskedICmpType)
502/// that both LHS and RHS satisfy
503static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
504 Value*& B, Value*& C,
505 Value*& D, Value*& E,
506 ICmpInst *LHS, ICmpInst *RHS) {
507 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
508 if (LHSCC != ICmpInst::ICMP_EQ && LHSCC != ICmpInst::ICMP_NE) return 0;
509 if (RHSCC != ICmpInst::ICMP_EQ && RHSCC != ICmpInst::ICMP_NE) return 0;
510 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
511 // vectors are not (yet?) supported
512 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
513
514 // Here comes the tricky part:
515 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
516 // and L11 & L12 == L21 & L22. The same goes for RHS.
517 // Now we must find those components L** and R**, that are equal, so
518 // that we can extract the parameters A, B, C, D, and E for the canonical
519 // above.
520 Value *L1 = LHS->getOperand(0);
521 Value *L2 = LHS->getOperand(1);
522 Value *L11,*L12,*L21,*L22;
523 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
524 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
525 L21 = L22 = 0;
526 }
527 else {
528 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
529 return 0;
530 std::swap(L1, L2);
531 L21 = L22 = 0;
532 }
533
534 Value *R1 = RHS->getOperand(0);
535 Value *R2 = RHS->getOperand(1);
536 Value *R11,*R12;
537 bool ok = false;
538 if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
539 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
540 A = R11; D = R12; E = R2; ok = true;
541 }
542 else
543 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
544 A = R12; D = R11; E = R2; ok = true;
545 }
546 }
547 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
548 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
549 A = R11; D = R12; E = R1; ok = true;
550 }
551 else
552 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
553 A = R12; D = R11; E = R1; ok = true;
554 }
555 else
556 return 0;
557 }
558 if (!ok)
559 return 0;
560
561 if (L11 == A) {
562 B = L12; C = L2;
563 }
564 else if (L12 == A) {
565 B = L11; C = L2;
566 }
567 else if (L21 == A) {
568 B = L22; C = L1;
569 }
570 else if (L22 == A) {
571 B = L21; C = L1;
572 }
573
574 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
575 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
576 return left_type & right_type;
577}
578/// foldLogOpOfMaskedICmps:
579/// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
580/// into a single (icmp(A & X) ==/!= Y)
581static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
582 ICmpInst::Predicate NEWCC,
583 llvm::InstCombiner::BuilderTy* Builder) {
584 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
585 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS);
586 if (mask == 0) return 0;
587
588 if (NEWCC == ICmpInst::ICMP_NE)
589 mask >>= 1; // treat "Not"-states as normal states
590
591 if (mask & FoldMskICmp_Mask_AllZeroes) {
592 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
593 // -> (icmp eq (A & (B|D)), 0)
594 Value* newOr = Builder->CreateOr(B, D);
595 Value* newAnd = Builder->CreateAnd(A, newOr);
596 // we can't use C as zero, because we might actually handle
597 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
598 // with B and D, having a single bit set
599 Value* zero = Constant::getNullValue(A->getType());
600 return Builder->CreateICmp(NEWCC, newAnd, zero);
601 }
602 else if (mask & FoldMskICmp_BMask_AllOnes) {
603 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
604 // -> (icmp eq (A & (B|D)), (B|D))
605 Value* newOr = Builder->CreateOr(B, D);
606 Value* newAnd = Builder->CreateAnd(A, newOr);
607 return Builder->CreateICmp(NEWCC, newAnd, newOr);
608 }
609 else if (mask & FoldMskICmp_AMask_AllOnes) {
610 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
611 // -> (icmp eq (A & (B&D)), A)
612 Value* newAnd1 = Builder->CreateAnd(B, D);
613 Value* newAnd = Builder->CreateAnd(A, newAnd1);
614 return Builder->CreateICmp(NEWCC, newAnd, A);
615 }
616 else if (mask & FoldMskICmp_BMask_Mixed) {
617 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
618 // We already know that B & C == C && D & E == E.
619 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
620 // C and E, which are shared by both the mask B and the mask D, don't
621 // contradict, then we can transform to
622 // -> (icmp eq (A & (B|D)), (C|E))
623 // Currently, we only handle the case of B, C, D, and E being constant.
624 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
625 if (BCst == 0) return 0;
626 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
627 if (DCst == 0) return 0;
628 // we can't simply use C and E, because we might actually handle
629 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
630 // with B and D, having a single bit set
631
632 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
633 if (CCst == 0) return 0;
634 if (LHS->getPredicate() != NEWCC)
635 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
636 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
637 if (ECst == 0) return 0;
638 if (RHS->getPredicate() != NEWCC)
639 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
640 ConstantInt* MCst = dyn_cast<ConstantInt>(
641 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
642 ConstantExpr::getXor(CCst, ECst)) );
643 // if there is a conflict we should actually return a false for the
644 // whole construct
645 if (!MCst->isZero())
646 return 0;
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000647 Value *newOr1 = Builder->CreateOr(B, D);
648 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
649 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000650 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
651 }
652 return 0;
653}
654
Chris Lattner0a8191e2010-01-05 07:50:36 +0000655/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000656Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000657 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
658
659 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
660 if (PredicatesFoldable(LHSCC, RHSCC)) {
661 if (LHS->getOperand(0) == RHS->getOperand(1) &&
662 LHS->getOperand(1) == RHS->getOperand(0))
663 LHS->swapOperands();
664 if (LHS->getOperand(0) == RHS->getOperand(0) &&
665 LHS->getOperand(1) == RHS->getOperand(1)) {
666 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
667 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
668 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000669 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000670 }
671 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000672
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000673 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
674 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
675 return V;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000676
677 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
678 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
679 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
680 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
681 if (LHSCst == 0 || RHSCst == 0) return 0;
682
683 if (LHSCst == RHSCst && LHSCC == RHSCC) {
684 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
685 // where C is a power of 2
686 if (LHSCC == ICmpInst::ICMP_ULT &&
687 LHSCst->getValue().isPowerOf2()) {
688 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000689 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000690 }
691
692 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
693 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
694 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000695 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000696 }
Benjamin Kramer272f2b02011-03-29 22:06:41 +0000697
698 // (icmp slt A, 0) & (icmp slt B, 0) --> (icmp slt (A&B), 0)
699 if (LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()) {
700 Value *NewAnd = Builder->CreateAnd(Val, Val2);
701 return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
702 }
703
704 // (icmp sgt A, -1) & (icmp sgt B, -1) --> (icmp sgt (A|B), -1)
705 if (LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
706 Value *NewOr = Builder->CreateOr(Val, Val2);
707 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
708 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000709 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000710
Benjamin Kramer101720f2011-04-28 20:09:57 +0000711 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000712 // where CMAX is the all ones value for the truncated type,
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000713 // iff the lower bits of C2 and CA are zero.
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000714 if (LHSCC == RHSCC && ICmpInst::isEquality(LHSCC) &&
715 LHS->hasOneUse() && RHS->hasOneUse()) {
716 Value *V;
717 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
718
719 // (trunc x) == C1 & (and x, CA) == C2
720 if (match(Val2, m_Trunc(m_Value(V))) &&
721 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
722 SmallCst = RHSCst;
723 BigCst = LHSCst;
724 }
725 // (and x, CA) == C2 & (trunc x) == C1
726 else if (match(Val, m_Trunc(m_Value(V))) &&
727 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
728 SmallCst = LHSCst;
729 BigCst = RHSCst;
730 }
731
732 if (SmallCst && BigCst) {
733 unsigned BigBitSize = BigCst->getType()->getBitWidth();
734 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
735
736 // Check that the low bits are zero.
737 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000738 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000739 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
740 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
741 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
742 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
743 }
744 }
745 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000746
747 // (X & C) == 0 & X > -1 -> (X & (C | SignBit)) == 0
748 if (LHS->hasOneUse() && RHS->hasOneUse() &&
749 ((LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero() &&
750 RHSCC == ICmpInst::ICMP_SGT && RHSCst->isAllOnesValue()) ||
751 (RHSCC == ICmpInst::ICMP_EQ && RHSCst->isZero() &&
752 LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()))) {
753 BinaryOperator *BO =
754 dyn_cast<BinaryOperator>(LHSCC == ICmpInst::ICMP_EQ ? Val : Val2);
755 ConstantInt *AndCst;
756 if (BO && match(BO, m_OneUse(m_And(m_Value(), m_ConstantInt(AndCst))))) {
757 APInt New = AndCst->getValue() | APInt::getSignBit(AndCst->getBitWidth());
758 BO->setOperand(1, ConstantInt::get(AndCst->getContext(), New));
759 return BO == Val ? LHS : RHS;
760 }
761 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000762
763 // From here on, we only handle:
764 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
765 if (Val != Val2) return 0;
766
767 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
768 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
769 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
770 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
771 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
772 return 0;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000773
774 // Make a constant range that's the intersection of the two icmp ranges.
775 // If the intersection is empty, we know that the result is false.
776 ConstantRange LHSRange =
777 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
778 ConstantRange RHSRange =
779 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
780
781 if (LHSRange.intersectWith(RHSRange).isEmptySet())
782 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
783
Chris Lattner0a8191e2010-01-05 07:50:36 +0000784 // We can't fold (ugt x, C) & (sgt x, C2).
785 if (!PredicatesFoldable(LHSCC, RHSCC))
786 return 0;
787
788 // Ensure that the larger constant is on the RHS.
789 bool ShouldSwap;
790 if (CmpInst::isSigned(LHSCC) ||
791 (ICmpInst::isEquality(LHSCC) &&
792 CmpInst::isSigned(RHSCC)))
793 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
794 else
795 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
796
797 if (ShouldSwap) {
798 std::swap(LHS, RHS);
799 std::swap(LHSCst, RHSCst);
800 std::swap(LHSCC, RHSCC);
801 }
802
Dan Gohman4a618822010-02-10 16:03:48 +0000803 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000804 // comparing a value against two constants and and'ing the result
805 // together. Because of the above check, we know that we only have
806 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
807 // (from the icmp folding check above), that the two constants
808 // are not equal and that the larger constant is on the RHS
809 assert(LHSCst != RHSCst && "Compares not folded above?");
810
811 switch (LHSCC) {
812 default: llvm_unreachable("Unknown integer condition code!");
813 case ICmpInst::ICMP_EQ:
814 switch (RHSCC) {
815 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000816 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
817 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
818 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000819 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000820 }
821 case ICmpInst::ICMP_NE:
822 switch (RHSCC) {
823 default: llvm_unreachable("Unknown integer condition code!");
824 case ICmpInst::ICMP_ULT:
825 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000826 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000827 break; // (X != 13 & X u< 15) -> no change
828 case ICmpInst::ICMP_SLT:
829 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000830 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000831 break; // (X != 13 & X s< 15) -> no change
832 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
833 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
834 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000835 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 case ICmpInst::ICMP_NE:
837 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
838 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
839 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Chris Lattner067459c2010-03-05 08:46:26 +0000840 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000841 }
842 break; // (X != 13 & X != 15) -> no change
843 }
844 break;
845 case ICmpInst::ICMP_ULT:
846 switch (RHSCC) {
847 default: llvm_unreachable("Unknown integer condition code!");
848 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
849 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000850 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000851 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
852 break;
853 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
854 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000855 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000856 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
857 break;
858 }
859 break;
860 case ICmpInst::ICMP_SLT:
861 switch (RHSCC) {
862 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000863 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
864 break;
865 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
866 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000867 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000868 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
869 break;
870 }
871 break;
872 case ICmpInst::ICMP_UGT:
873 switch (RHSCC) {
874 default: llvm_unreachable("Unknown integer condition code!");
875 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
876 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000877 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000878 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
879 break;
880 case ICmpInst::ICMP_NE:
881 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000882 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000883 break; // (X u> 13 & X != 15) -> no change
884 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000885 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000886 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
887 break;
888 }
889 break;
890 case ICmpInst::ICMP_SGT:
891 switch (RHSCC) {
892 default: llvm_unreachable("Unknown integer condition code!");
893 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
894 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000895 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000896 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
897 break;
898 case ICmpInst::ICMP_NE:
899 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000900 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000901 break; // (X s> 13 & X != 15) -> no change
902 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +0000903 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000904 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
905 break;
906 }
907 break;
908 }
909
910 return 0;
911}
912
Chris Lattner067459c2010-03-05 08:46:26 +0000913/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
914/// instcombine, this returns a Value which should already be inserted into the
915/// function.
916Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000917 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
918 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
919 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
920 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
921 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
922 // If either of the constants are nans, then the whole thing returns
923 // false.
924 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +0000925 return ConstantInt::getFalse(LHS->getContext());
926 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927 }
928
929 // Handle vector zeros. This occurs because the canonical form of
930 // "fcmp ord x,x" is "fcmp ord x, 0".
931 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
932 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000933 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934 return 0;
935 }
936
937 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
938 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
939 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
940
941
942 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
943 // Swap RHS operands to match LHS.
944 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
945 std::swap(Op1LHS, Op1RHS);
946 }
947
948 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
949 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
950 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +0000951 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000952 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +0000953 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000954 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000955 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000957 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958
959 bool Op0Ordered;
960 bool Op1Ordered;
961 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
962 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
963 if (Op1Pred == 0) {
964 std::swap(LHS, RHS);
965 std::swap(Op0Pred, Op1Pred);
966 std::swap(Op0Ordered, Op1Ordered);
967 }
968 if (Op0Pred == 0) {
969 // uno && ueq -> uno && (uno || eq) -> ueq
970 // ord && olt -> ord && (ord && lt) -> olt
971 if (Op0Ordered == Op1Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +0000972 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000973
974 // uno && oeq -> uno && (ord && eq) -> false
975 // uno && ord -> false
976 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +0000977 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000978 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +0000979 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000980 }
981 }
982
983 return 0;
984}
985
986
987Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000988 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
990
991 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
992 return ReplaceInstUsesWith(I, V);
993
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000994 // (A|B)&(A|C) -> A|(B&C) etc
995 if (Value *V = SimplifyUsingDistributiveLaws(I))
996 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000997
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 // See if we can simplify any instructions used by the instruction whose sole
999 // purpose is to compute bits we don't care about.
1000 if (SimplifyDemandedInstructionBits(I))
1001 return &I;
1002
1003 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1004 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001005
1006 // Optimize a variety of ((val OP C1) & C2) combinations...
1007 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1008 Value *Op0LHS = Op0I->getOperand(0);
1009 Value *Op0RHS = Op0I->getOperand(1);
1010 switch (Op0I->getOpcode()) {
1011 default: break;
1012 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001013 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001014 // If the mask is only needed on one incoming arm, push it up.
1015 if (!Op0I->hasOneUse()) break;
1016
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001017 APInt NotAndRHS(~AndRHSMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001018 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1019 // Not masking anything out for the LHS, move to RHS.
1020 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1021 Op0RHS->getName()+".masked");
1022 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1023 }
1024 if (!isa<Constant>(Op0RHS) &&
1025 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1026 // Not masking anything out for the RHS, move to LHS.
1027 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1028 Op0LHS->getName()+".masked");
1029 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1030 }
1031
1032 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001033 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001034 case Instruction::Add:
1035 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1036 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1037 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1038 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1039 return BinaryOperator::CreateAnd(V, AndRHS);
1040 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1041 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1042 break;
1043
1044 case Instruction::Sub:
1045 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1046 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1047 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1048 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1049 return BinaryOperator::CreateAnd(V, AndRHS);
1050
1051 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1052 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001053 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001054 uint32_t BitWidth = AndRHSMask.getBitWidth();
1055 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1056 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1057
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001058 if (MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001059 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1060 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1061 }
1062 }
1063 break;
1064
1065 case Instruction::Shl:
1066 case Instruction::LShr:
1067 // (1 << x) & 1 --> zext(x == 0)
1068 // (1 >> x) & 1 --> zext(x == 0)
1069 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1070 Value *NewICmp =
1071 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1072 return new ZExtInst(NewICmp, I.getType());
1073 }
1074 break;
1075 }
Chris Lattner9f0ac0d2011-02-15 01:56:08 +00001076
Chris Lattner0a8191e2010-01-05 07:50:36 +00001077 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1078 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1079 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001080 }
1081
1082 // If this is an integer truncation, and if the source is an 'and' with
1083 // immediate, transform it. This frequently occurs for bitfield accesses.
1084 {
1085 Value *X = 0; ConstantInt *YC = 0;
1086 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1087 // Change: and (trunc (and X, YC) to T), C2
1088 // into : and (trunc X to T), trunc(YC) & C2
1089 // This will fold the two constants together, which may allow
1090 // other simplifications.
1091 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1092 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1093 C3 = ConstantExpr::getAnd(C3, AndRHS);
1094 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001095 }
1096 }
1097
1098 // Try to fold constant and into select arguments.
1099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1100 if (Instruction *R = FoldOpIntoSelect(I, SI))
1101 return R;
1102 if (isa<PHINode>(Op0))
1103 if (Instruction *NV = FoldOpIntoPhi(I))
1104 return NV;
1105 }
1106
1107
1108 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1109 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1110 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1111 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1112 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1113 I.getName()+".demorgan");
1114 return BinaryOperator::CreateNot(Or);
1115 }
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001116
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117 {
1118 Value *A = 0, *B = 0, *C = 0, *D = 0;
1119 // (A|B) & ~(A&B) -> A^B
1120 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1121 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1122 ((A == C && B == D) || (A == D && B == C)))
1123 return BinaryOperator::CreateXor(A, B);
1124
1125 // ~(A&B) & (A|B) -> A^B
1126 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1127 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1128 ((A == C && B == D) || (A == D && B == C)))
1129 return BinaryOperator::CreateXor(A, B);
1130
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001131 // A&(A^B) => A & ~B
1132 {
1133 Value *tmpOp0 = Op0;
1134 Value *tmpOp1 = Op1;
1135 if (Op0->hasOneUse() &&
1136 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1137 if (A == Op1 || B == Op1 ) {
1138 tmpOp1 = Op0;
1139 tmpOp0 = Op1;
1140 // Simplify below
1141 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001142 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001144 if (tmpOp1->hasOneUse() &&
1145 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1146 if (B == tmpOp0) {
1147 std::swap(A, B);
1148 }
1149 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1150 // A is originally -1 (or a vector of -1 and undefs), then we enter
1151 // an endless loop. By checking that A is non-constant we ensure that
1152 // we will never get to the loop.
1153 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001154 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001155 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001156 }
1157
1158 // (A&((~A)|B)) -> A&B
1159 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1160 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1161 return BinaryOperator::CreateAnd(A, Op1);
1162 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1163 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1164 return BinaryOperator::CreateAnd(A, Op0);
1165 }
1166
1167 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1168 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +00001169 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1170 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +00001171
1172 // If and'ing two fcmp, try combine them into one.
1173 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1174 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001175 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1176 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +00001177
1178
Chris Lattner0a8191e2010-01-05 07:50:36 +00001179 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1180 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001181 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001182 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner4e8137d2010-02-11 06:26:33 +00001183 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1184 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001185 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001186 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1187
1188 // Only do this if the casts both really cause code to be generated.
1189 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1190 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1191 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001192 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1193 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001194
1195 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1196 // cast is otherwise not optimizable. This happens for vector sexts.
1197 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1198 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001199 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001200 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner4e8137d2010-02-11 06:26:33 +00001201
1202 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1203 // cast is otherwise not optimizable. This happens for vector sexts.
1204 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1205 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001206 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001207 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001208 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001209 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001210
1211 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1212 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1213 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1214 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1215 SI0->getOperand(1) == SI1->getOperand(1) &&
1216 (SI0->hasOneUse() || SI1->hasOneUse())) {
1217 Value *NewOp =
1218 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1219 SI0->getName());
1220 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1221 SI1->getOperand(1));
1222 }
1223 }
1224
Chris Lattner0a8191e2010-01-05 07:50:36 +00001225 return Changed ? &I : 0;
1226}
1227
1228/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1229/// capable of providing pieces of a bswap. The subexpression provides pieces
1230/// of a bswap if it is proven that each of the non-zero bytes in the output of
1231/// the expression came from the corresponding "byte swapped" byte in some other
1232/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1233/// we know that the expression deposits the low byte of %X into the high byte
1234/// of the bswap result and that all other bytes are zero. This expression is
1235/// accepted, the high byte of ByteValues is set to X to indicate a correct
1236/// match.
1237///
1238/// This function returns true if the match was unsuccessful and false if so.
1239/// On entry to the function the "OverallLeftShift" is a signed integer value
1240/// indicating the number of bytes that the subexpression is later shifted. For
1241/// example, if the expression is later right shifted by 16 bits, the
1242/// OverallLeftShift value would be -2 on entry. This is used to specify which
1243/// byte of ByteValues is actually being set.
1244///
1245/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1246/// byte is masked to zero by a user. For example, in (X & 255), X will be
1247/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1248/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1249/// always in the local (OverallLeftShift) coordinate space.
1250///
1251static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1252 SmallVector<Value*, 8> &ByteValues) {
1253 if (Instruction *I = dyn_cast<Instruction>(V)) {
1254 // If this is an or instruction, it may be an inner node of the bswap.
1255 if (I->getOpcode() == Instruction::Or) {
1256 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1257 ByteValues) ||
1258 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1259 ByteValues);
1260 }
1261
1262 // If this is a logical shift by a constant multiple of 8, recurse with
1263 // OverallLeftShift and ByteMask adjusted.
1264 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1265 unsigned ShAmt =
1266 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1267 // Ensure the shift amount is defined and of a byte value.
1268 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1269 return true;
1270
1271 unsigned ByteShift = ShAmt >> 3;
1272 if (I->getOpcode() == Instruction::Shl) {
1273 // X << 2 -> collect(X, +2)
1274 OverallLeftShift += ByteShift;
1275 ByteMask >>= ByteShift;
1276 } else {
1277 // X >>u 2 -> collect(X, -2)
1278 OverallLeftShift -= ByteShift;
1279 ByteMask <<= ByteShift;
1280 ByteMask &= (~0U >> (32-ByteValues.size()));
1281 }
1282
1283 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1284 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1285
1286 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1287 ByteValues);
1288 }
1289
1290 // If this is a logical 'and' with a mask that clears bytes, clear the
1291 // corresponding bytes in ByteMask.
1292 if (I->getOpcode() == Instruction::And &&
1293 isa<ConstantInt>(I->getOperand(1))) {
1294 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1295 unsigned NumBytes = ByteValues.size();
1296 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1297 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1298
1299 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1300 // If this byte is masked out by a later operation, we don't care what
1301 // the and mask is.
1302 if ((ByteMask & (1 << i)) == 0)
1303 continue;
1304
1305 // If the AndMask is all zeros for this byte, clear the bit.
1306 APInt MaskB = AndMask & Byte;
1307 if (MaskB == 0) {
1308 ByteMask &= ~(1U << i);
1309 continue;
1310 }
1311
1312 // If the AndMask is not all ones for this byte, it's not a bytezap.
1313 if (MaskB != Byte)
1314 return true;
1315
1316 // Otherwise, this byte is kept.
1317 }
1318
1319 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1320 ByteValues);
1321 }
1322 }
1323
1324 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1325 // the input value to the bswap. Some observations: 1) if more than one byte
1326 // is demanded from this input, then it could not be successfully assembled
1327 // into a byteswap. At least one of the two bytes would not be aligned with
1328 // their ultimate destination.
1329 if (!isPowerOf2_32(ByteMask)) return true;
1330 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1331
1332 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1333 // is demanded, it needs to go into byte 0 of the result. This means that the
1334 // byte needs to be shifted until it lands in the right byte bucket. The
1335 // shift amount depends on the position: if the byte is coming from the high
1336 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1337 // low part, it must be shifted left.
1338 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1339 if (InputByteNo < ByteValues.size()/2) {
1340 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1341 return true;
1342 } else {
1343 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1344 return true;
1345 }
1346
1347 // If the destination byte value is already defined, the values are or'd
1348 // together, which isn't a bswap (unless it's an or of the same bits).
1349 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1350 return true;
1351 ByteValues[DestByteNo] = V;
1352 return false;
1353}
1354
1355/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1356/// If so, insert the new bswap intrinsic and return it.
1357Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001358 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001359 if (!ITy || ITy->getBitWidth() % 16 ||
1360 // ByteMask only allows up to 32-byte values.
1361 ITy->getBitWidth() > 32*8)
1362 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1363
1364 /// ByteValues - For each byte of the result, we keep track of which value
1365 /// defines each byte.
1366 SmallVector<Value*, 8> ByteValues;
1367 ByteValues.resize(ITy->getBitWidth()/8);
1368
1369 // Try to find all the pieces corresponding to the bswap.
1370 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1371 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1372 return 0;
1373
1374 // Check to see if all of the bytes come from the same value.
1375 Value *V = ByteValues[0];
1376 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1377
1378 // Check to make sure that all of the bytes come from the same value.
1379 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1380 if (ByteValues[i] != V)
1381 return 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001382 Module *M = I.getParent()->getParent()->getParent();
Benjamin Kramere6e19332011-07-14 17:45:39 +00001383 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001384 return CallInst::Create(F, V);
1385}
1386
1387/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1388/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1389/// we can simplify this expression to "cond ? C : D or B".
1390static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1391 Value *C, Value *D) {
1392 // If A is not a select of -1/0, this cannot match.
1393 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001394 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001395 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001396 return 0;
1397
1398 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001399 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001400 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001401 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001402 return SelectInst::Create(Cond, C, B);
1403
Chris Lattner0a8191e2010-01-05 07:50:36 +00001404 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001405 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001406 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001407 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 return 0;
1410}
1411
Chris Lattner067459c2010-03-05 08:46:26 +00001412/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1413Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1415
1416 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1417 if (PredicatesFoldable(LHSCC, RHSCC)) {
1418 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1419 LHS->getOperand(1) == RHS->getOperand(0))
1420 LHS->swapOperands();
1421 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1422 LHS->getOperand(1) == RHS->getOperand(1)) {
1423 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1424 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1425 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001426 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001427 }
1428 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001429
1430 // handle (roughly):
1431 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1432 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1433 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001434
Chris Lattner0a8191e2010-01-05 07:50:36 +00001435 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1436 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1437 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1438 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1439 if (LHSCst == 0 || RHSCst == 0) return 0;
1440
Owen Anderson8f306a72010-08-02 09:32:13 +00001441 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1442 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1443 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1444 Value *NewOr = Builder->CreateOr(Val, Val2);
1445 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1446 }
Benjamin Kramer272f2b02011-03-29 22:06:41 +00001447
1448 // (icmp slt A, 0) | (icmp slt B, 0) --> (icmp slt (A|B), 0)
1449 if (LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()) {
1450 Value *NewOr = Builder->CreateOr(Val, Val2);
1451 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1452 }
1453
1454 // (icmp sgt A, -1) | (icmp sgt B, -1) --> (icmp sgt (A&B), -1)
1455 if (LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
1456 Value *NewAnd = Builder->CreateAnd(Val, Val2);
1457 return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
1458 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001459 }
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001460
Benjamin Kramerda37e152012-01-08 18:32:24 +00001461 // (X & C) != 0 & X < 0 -> (X & (C | SignBit)) != 0
1462 if (LHS->hasOneUse() && RHS->hasOneUse() &&
1463 ((LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero() &&
1464 RHSCC == ICmpInst::ICMP_SLT && RHSCst->isZero()) ||
1465 (RHSCC == ICmpInst::ICMP_NE && RHSCst->isZero() &&
1466 LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()))) {
1467 BinaryOperator *BO =
1468 dyn_cast<BinaryOperator>(LHSCC == ICmpInst::ICMP_NE ? Val : Val2);
1469 ConstantInt *AndCst;
1470 if (BO && match(BO, m_OneUse(m_And(m_Value(), m_ConstantInt(AndCst))))) {
1471 APInt New = AndCst->getValue() | APInt::getSignBit(AndCst->getBitWidth());
1472 BO->setOperand(1, ConstantInt::get(AndCst->getContext(), New));
1473 return BO == Val ? LHS : RHS;
1474 }
1475 }
1476
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001477 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001478 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001479 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001480 ConstantInt *AddCst;
1481 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1482 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001483 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001484 }
1485
Chris Lattner0a8191e2010-01-05 07:50:36 +00001486 // From here on, we only handle:
1487 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1488 if (Val != Val2) return 0;
1489
1490 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1491 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1492 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1493 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1494 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1495 return 0;
1496
1497 // We can't fold (ugt x, C) | (sgt x, C2).
1498 if (!PredicatesFoldable(LHSCC, RHSCC))
1499 return 0;
1500
1501 // Ensure that the larger constant is on the RHS.
1502 bool ShouldSwap;
1503 if (CmpInst::isSigned(LHSCC) ||
1504 (ICmpInst::isEquality(LHSCC) &&
1505 CmpInst::isSigned(RHSCC)))
1506 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1507 else
1508 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1509
1510 if (ShouldSwap) {
1511 std::swap(LHS, RHS);
1512 std::swap(LHSCst, RHSCst);
1513 std::swap(LHSCC, RHSCC);
1514 }
1515
Dan Gohman4a618822010-02-10 16:03:48 +00001516 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001517 // comparing a value against two constants and or'ing the result
1518 // together. Because of the above check, we know that we only have
1519 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1520 // icmp folding check above), that the two constants are not
1521 // equal.
1522 assert(LHSCst != RHSCst && "Compares not folded above?");
1523
1524 switch (LHSCC) {
1525 default: llvm_unreachable("Unknown integer condition code!");
1526 case ICmpInst::ICMP_EQ:
1527 switch (RHSCC) {
1528 default: llvm_unreachable("Unknown integer condition code!");
1529 case ICmpInst::ICMP_EQ:
1530 if (LHSCst == SubOne(RHSCst)) {
1531 // (X == 13 | X == 14) -> X-13 <u 2
1532 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1533 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1534 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner067459c2010-03-05 08:46:26 +00001535 return Builder->CreateICmpULT(Add, AddCST);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001536 }
1537 break; // (X == 13 | X == 15) -> no change
1538 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1539 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1540 break;
1541 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1542 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1543 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001544 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001545 }
1546 break;
1547 case ICmpInst::ICMP_NE:
1548 switch (RHSCC) {
1549 default: llvm_unreachable("Unknown integer condition code!");
1550 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1551 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1552 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001553 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001554 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1555 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1556 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001557 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001558 }
1559 break;
1560 case ICmpInst::ICMP_ULT:
1561 switch (RHSCC) {
1562 default: llvm_unreachable("Unknown integer condition code!");
1563 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1564 break;
1565 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1566 // If RHSCst is [us]MAXINT, it is always false. Not handling
1567 // this can cause overflow.
1568 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001569 return LHS;
1570 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001571 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1572 break;
1573 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1574 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001575 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001576 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1577 break;
1578 }
1579 break;
1580 case ICmpInst::ICMP_SLT:
1581 switch (RHSCC) {
1582 default: llvm_unreachable("Unknown integer condition code!");
1583 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1584 break;
1585 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1586 // If RHSCst is [us]MAXINT, it is always false. Not handling
1587 // this can cause overflow.
1588 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001589 return LHS;
1590 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001591 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1592 break;
1593 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1594 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001595 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001596 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1597 break;
1598 }
1599 break;
1600 case ICmpInst::ICMP_UGT:
1601 switch (RHSCC) {
1602 default: llvm_unreachable("Unknown integer condition code!");
1603 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1604 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001605 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001606 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1607 break;
1608 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1609 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001610 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001611 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1612 break;
1613 }
1614 break;
1615 case ICmpInst::ICMP_SGT:
1616 switch (RHSCC) {
1617 default: llvm_unreachable("Unknown integer condition code!");
1618 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1619 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001620 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001621 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1622 break;
1623 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1624 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001625 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001626 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1627 break;
1628 }
1629 break;
1630 }
1631 return 0;
1632}
1633
Chris Lattner067459c2010-03-05 08:46:26 +00001634/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1635/// instcombine, this returns a Value which should already be inserted into the
1636/// function.
1637Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001638 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1639 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1640 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1641 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1642 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1643 // If either of the constants are nans, then the whole thing returns
1644 // true.
1645 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +00001646 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001647
1648 // Otherwise, no need to compare the two constants, compare the
1649 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001650 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001651 }
1652
1653 // Handle vector zeros. This occurs because the canonical form of
1654 // "fcmp uno x,x" is "fcmp uno x, 0".
1655 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1656 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001657 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001658
1659 return 0;
1660 }
1661
1662 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1663 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1664 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1665
1666 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1667 // Swap RHS operands to match LHS.
1668 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1669 std::swap(Op1LHS, Op1RHS);
1670 }
1671 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1672 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1673 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001674 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001676 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001677 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001678 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001679 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001680 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001681 bool Op0Ordered;
1682 bool Op1Ordered;
1683 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1684 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1685 if (Op0Ordered == Op1Ordered) {
1686 // If both are ordered or unordered, return a new fcmp with
1687 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001688 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001689 }
1690 }
1691 return 0;
1692}
1693
1694/// FoldOrWithConstants - This helper function folds:
1695///
1696/// ((A | B) & C1) | (B & C2)
1697///
1698/// into:
1699///
1700/// (A & C1) | B
1701///
1702/// when the XOR of the two constants is "all ones" (-1).
1703Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1704 Value *A, Value *B, Value *C) {
1705 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1706 if (!CI1) return 0;
1707
1708 Value *V1 = 0;
1709 ConstantInt *CI2 = 0;
1710 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1711
1712 APInt Xor = CI1->getValue() ^ CI2->getValue();
1713 if (!Xor.isAllOnesValue()) return 0;
1714
1715 if (V1 == A || V1 == B) {
1716 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1717 return BinaryOperator::CreateOr(NewOp, V1);
1718 }
1719
1720 return 0;
1721}
1722
1723Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001724 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1726
1727 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1728 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001729
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001730 // (A&B)|(A&C) -> A&(B|C) etc
1731 if (Value *V = SimplifyUsingDistributiveLaws(I))
1732 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001733
Chris Lattner0a8191e2010-01-05 07:50:36 +00001734 // See if we can simplify any instructions used by the instruction whose sole
1735 // purpose is to compute bits we don't care about.
1736 if (SimplifyDemandedInstructionBits(I))
1737 return &I;
1738
1739 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1740 ConstantInt *C1 = 0; Value *X = 0;
1741 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Bill Wendlingaf13d822010-03-03 00:35:56 +00001742 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001743 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001744 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001745 Op0->hasOneUse()) {
1746 Value *Or = Builder->CreateOr(X, RHS);
1747 Or->takeName(Op0);
1748 return BinaryOperator::CreateAnd(Or,
1749 ConstantInt::get(I.getContext(),
1750 RHS->getValue() | C1->getValue()));
1751 }
1752
1753 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1754 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1755 Op0->hasOneUse()) {
1756 Value *Or = Builder->CreateOr(X, RHS);
1757 Or->takeName(Op0);
1758 return BinaryOperator::CreateXor(Or,
1759 ConstantInt::get(I.getContext(),
1760 C1->getValue() & ~RHS->getValue()));
1761 }
1762
1763 // Try to fold constant and into select arguments.
1764 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1765 if (Instruction *R = FoldOpIntoSelect(I, SI))
1766 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001767
Chris Lattner0a8191e2010-01-05 07:50:36 +00001768 if (isa<PHINode>(Op0))
1769 if (Instruction *NV = FoldOpIntoPhi(I))
1770 return NV;
1771 }
1772
1773 Value *A = 0, *B = 0;
1774 ConstantInt *C1 = 0, *C2 = 0;
1775
1776 // (A | B) | C and A | (B | C) -> bswap if possible.
1777 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1778 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1779 match(Op1, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb9400912011-02-09 17:00:45 +00001780 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1781 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 if (Instruction *BSwap = MatchBSwap(I))
1783 return BSwap;
1784 }
1785
1786 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1787 if (Op0->hasOneUse() &&
1788 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1789 MaskedValueIsZero(Op1, C1->getValue())) {
1790 Value *NOr = Builder->CreateOr(A, Op1);
1791 NOr->takeName(Op0);
1792 return BinaryOperator::CreateXor(NOr, C1);
1793 }
1794
1795 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1796 if (Op1->hasOneUse() &&
1797 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1798 MaskedValueIsZero(Op0, C1->getValue())) {
1799 Value *NOr = Builder->CreateOr(A, Op0);
1800 NOr->takeName(Op0);
1801 return BinaryOperator::CreateXor(NOr, C1);
1802 }
1803
1804 // (A & C)|(B & D)
1805 Value *C = 0, *D = 0;
1806 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1807 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001808 Value *V1 = 0, *V2 = 0;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 C1 = dyn_cast<ConstantInt>(C);
1810 C2 = dyn_cast<ConstantInt>(D);
1811 if (C1 && C2) { // (A & C1)|(B & C2)
1812 // If we have: ((V + N) & C1) | (V & C2)
1813 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1814 // replace with V+N.
1815 if (C1->getValue() == ~C2->getValue()) {
1816 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1817 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1818 // Add commutes, try both ways.
1819 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1820 return ReplaceInstUsesWith(I, A);
1821 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1822 return ReplaceInstUsesWith(I, A);
1823 }
1824 // Or commutes, try both ways.
1825 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1826 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1827 // Add commutes, try both ways.
1828 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1829 return ReplaceInstUsesWith(I, B);
1830 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1831 return ReplaceInstUsesWith(I, B);
1832 }
1833 }
1834
Chris Lattner0a8191e2010-01-05 07:50:36 +00001835 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00001836 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1837 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1839 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1840 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1841 return BinaryOperator::CreateAnd(A,
1842 ConstantInt::get(A->getContext(),
1843 C1->getValue()|C2->getValue()));
1844 // Or commutes, try both ways.
1845 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1846 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1847 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1848 return BinaryOperator::CreateAnd(B,
1849 ConstantInt::get(B->getContext(),
1850 C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001851
1852 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1853 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1854 ConstantInt *C3 = 0, *C4 = 0;
1855 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1856 (C3->getValue() & ~C1->getValue()) == 0 &&
1857 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1858 (C4->getValue() & ~C2->getValue()) == 0) {
1859 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1860 return BinaryOperator::CreateAnd(V2,
1861 ConstantInt::get(B->getContext(),
1862 C1->getValue()|C2->getValue()));
1863 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001864 }
1865 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001866
Chris Lattner8e2c4712010-02-02 02:43:51 +00001867 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1868 // Don't do this for vector select idioms, the code generator doesn't handle
1869 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00001870 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00001871 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1872 return Match;
1873 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1874 return Match;
1875 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1876 return Match;
1877 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1878 return Match;
1879 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001880
1881 // ((A&~B)|(~A&B)) -> A^B
1882 if ((match(C, m_Not(m_Specific(D))) &&
1883 match(B, m_Not(m_Specific(A)))))
1884 return BinaryOperator::CreateXor(A, D);
1885 // ((~B&A)|(~A&B)) -> A^B
1886 if ((match(A, m_Not(m_Specific(D))) &&
1887 match(B, m_Not(m_Specific(C)))))
1888 return BinaryOperator::CreateXor(C, D);
1889 // ((A&~B)|(B&~A)) -> A^B
1890 if ((match(C, m_Not(m_Specific(B))) &&
1891 match(D, m_Not(m_Specific(A)))))
1892 return BinaryOperator::CreateXor(A, B);
1893 // ((~B&A)|(B&~A)) -> A^B
1894 if ((match(A, m_Not(m_Specific(B))) &&
1895 match(D, m_Not(m_Specific(C)))))
1896 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00001897
1898 // ((A|B)&1)|(B&-2) -> (A&1) | B
1899 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1900 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1901 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1902 if (Ret) return Ret;
1903 }
1904 // (B&-2)|((A|B)&1) -> (A&1) | B
1905 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1906 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1907 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1908 if (Ret) return Ret;
1909 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 }
1911
1912 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1913 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1914 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1915 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1916 SI0->getOperand(1) == SI1->getOperand(1) &&
1917 (SI0->hasOneUse() || SI1->hasOneUse())) {
1918 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1919 SI0->getName());
1920 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1921 SI1->getOperand(1));
1922 }
1923 }
1924
Chris Lattner0a8191e2010-01-05 07:50:36 +00001925 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1926 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1927 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1928 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1929 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1930 I.getName()+".demorgan");
1931 return BinaryOperator::CreateNot(And);
1932 }
1933
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001934 // Canonicalize xor to the RHS.
1935 if (match(Op0, m_Xor(m_Value(), m_Value())))
1936 std::swap(Op0, Op1);
1937
1938 // A | ( A ^ B) -> A | B
1939 // A | (~A ^ B) -> A | ~B
1940 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1941 if (Op0 == A || Op0 == B)
1942 return BinaryOperator::CreateOr(A, B);
1943
1944 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1945 Value *Not = Builder->CreateNot(B, B->getName()+".not");
1946 return BinaryOperator::CreateOr(Not, Op0);
1947 }
1948 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1949 Value *Not = Builder->CreateNot(A, A->getName()+".not");
1950 return BinaryOperator::CreateOr(Not, Op0);
1951 }
1952 }
1953
1954 // A | ~(A | B) -> A | ~B
1955 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001956 if (match(Op1, m_Not(m_Value(A))))
1957 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001958 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1959 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1960 B->getOpcode() == Instruction::Xor)) {
1961 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1962 B->getOperand(0);
1963 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1964 return BinaryOperator::CreateOr(Not, Op0);
1965 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001966
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1968 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00001969 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1970 return ReplaceInstUsesWith(I, Res);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001971
Chris Lattner4e8137d2010-02-11 06:26:33 +00001972 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1973 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1974 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001975 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1976 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +00001977
Chris Lattner0a8191e2010-01-05 07:50:36 +00001978 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1979 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00001980 CastInst *Op1C = dyn_cast<CastInst>(Op1);
1981 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00001982 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00001983 if (SrcTy == Op1C->getOperand(0)->getType() &&
1984 SrcTy->isIntOrIntVectorTy()) {
1985 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00001986
Chris Lattner311aa632011-01-15 05:40:29 +00001987 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1988 // Only do this if the casts both really cause code to be
1989 // generated.
1990 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1991 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1992 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1993 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001994 }
Chris Lattner311aa632011-01-15 05:40:29 +00001995
1996 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1997 // cast is otherwise not optimizable. This happens for vector sexts.
1998 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1999 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2000 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2001 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2002
2003 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2004 // cast is otherwise not optimizable. This happens for vector sexts.
2005 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2006 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2007 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2008 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002009 }
Chris Lattner311aa632011-01-15 05:40:29 +00002010 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002011 }
Eli Friedman23956262011-04-14 22:41:27 +00002012
2013 // or(sext(A), B) -> A ? -1 : B where A is an i1
2014 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2015 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2016 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2017 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2018 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2019
Owen Andersonc237a842010-09-13 17:59:27 +00002020 // Note: If we've gotten to the point of visiting the outer OR, then the
2021 // inner one couldn't be simplified. If it was a constant, then it won't
2022 // be simplified by a later pass either, so we try swapping the inner/outer
2023 // ORs in the hopes that we'll be able to simplify it this way.
2024 // (X|C) | V --> (X|V) | C
2025 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2026 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2027 Value *Inner = Builder->CreateOr(A, Op1);
2028 Inner->takeName(Op0);
2029 return BinaryOperator::CreateOr(Inner, C1);
2030 }
2031
Chris Lattner0a8191e2010-01-05 07:50:36 +00002032 return Changed ? &I : 0;
2033}
2034
2035Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002036 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2038
Duncan Sandsc89ac072010-11-17 18:52:15 +00002039 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2040 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002042 // (A&B)^(A&C) -> A&(B^C) etc
2043 if (Value *V = SimplifyUsingDistributiveLaws(I))
2044 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002045
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 // See if we can simplify any instructions used by the instruction whose sole
2047 // purpose is to compute bits we don't care about.
2048 if (SimplifyDemandedInstructionBits(I))
2049 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002050
2051 // Is this a ~ operation?
2052 if (Value *NotOp = dyn_castNotVal(&I)) {
2053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2054 if (Op0I->getOpcode() == Instruction::And ||
2055 Op0I->getOpcode() == Instruction::Or) {
2056 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2057 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2058 if (dyn_castNotVal(Op0I->getOperand(1)))
2059 Op0I->swapOperands();
2060 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2061 Value *NotY =
2062 Builder->CreateNot(Op0I->getOperand(1),
2063 Op0I->getOperand(1)->getName()+".not");
2064 if (Op0I->getOpcode() == Instruction::And)
2065 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2066 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2067 }
2068
2069 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2070 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2071 if (isFreeToInvert(Op0I->getOperand(0)) &&
2072 isFreeToInvert(Op0I->getOperand(1))) {
2073 Value *NotX =
2074 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2075 Value *NotY =
2076 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2077 if (Op0I->getOpcode() == Instruction::And)
2078 return BinaryOperator::CreateOr(NotX, NotY);
2079 return BinaryOperator::CreateAnd(NotX, NotY);
2080 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002081
2082 } else if (Op0I->getOpcode() == Instruction::AShr) {
2083 // ~(~X >>s Y) --> (X >>s Y)
2084 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2085 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 }
2087 }
2088 }
2089
2090
2091 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00002092 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002093 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002094 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2095 return CmpInst::Create(CI->getOpcode(),
2096 CI->getInversePredicate(),
2097 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002098
2099 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2100 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2101 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2102 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2103 Instruction::CastOps Opcode = Op0C->getOpcode();
2104 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2105 (RHS == ConstantExpr::getCast(Opcode,
2106 ConstantInt::getTrue(I.getContext()),
2107 Op0C->getDestTy()))) {
2108 CI->setPredicate(CI->getInversePredicate());
2109 return CastInst::Create(Opcode, CI, Op0C->getType());
2110 }
2111 }
2112 }
2113 }
2114
2115 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2116 // ~(c-X) == X-c-1 == X+(-c-1)
2117 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2118 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2119 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2120 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2121 ConstantInt::get(I.getType(), 1));
2122 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2123 }
2124
2125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2126 if (Op0I->getOpcode() == Instruction::Add) {
2127 // ~(X-c) --> (-c-1)-X
2128 if (RHS->isAllOnesValue()) {
2129 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2130 return BinaryOperator::CreateSub(
2131 ConstantExpr::getSub(NegOp0CI,
2132 ConstantInt::get(I.getType(), 1)),
2133 Op0I->getOperand(0));
2134 } else if (RHS->getValue().isSignBit()) {
2135 // (X + C) ^ signbit -> (X + C + signbit)
2136 Constant *C = ConstantInt::get(I.getContext(),
2137 RHS->getValue() + Op0CI->getValue());
2138 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2139
2140 }
2141 } else if (Op0I->getOpcode() == Instruction::Or) {
2142 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2143 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2144 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2145 // Anything in both C1 and C2 is known to be zero, remove it from
2146 // NewRHS.
2147 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2148 NewRHS = ConstantExpr::getAnd(NewRHS,
2149 ConstantExpr::getNot(CommonBits));
2150 Worklist.Add(Op0I);
2151 I.setOperand(0, Op0I->getOperand(0));
2152 I.setOperand(1, NewRHS);
2153 return &I;
2154 }
2155 }
2156 }
2157 }
2158
2159 // Try to fold constant and into select arguments.
2160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2161 if (Instruction *R = FoldOpIntoSelect(I, SI))
2162 return R;
2163 if (isa<PHINode>(Op0))
2164 if (Instruction *NV = FoldOpIntoPhi(I))
2165 return NV;
2166 }
2167
Chris Lattner0a8191e2010-01-05 07:50:36 +00002168 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2169 if (Op1I) {
2170 Value *A, *B;
2171 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2172 if (A == Op0) { // B^(B|A) == (A|B)^B
2173 Op1I->swapOperands();
2174 I.swapOperands();
2175 std::swap(Op0, Op1);
2176 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2177 I.swapOperands(); // Simplified below.
2178 std::swap(Op0, Op1);
2179 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002180 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2181 Op1I->hasOneUse()){
2182 if (A == Op0) { // A^(A&B) -> A^(B&A)
2183 Op1I->swapOperands();
2184 std::swap(A, B);
2185 }
2186 if (B == Op0) { // A^(B&A) -> (B&A)^A
2187 I.swapOperands(); // Simplified below.
2188 std::swap(Op0, Op1);
2189 }
2190 }
2191 }
2192
2193 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2194 if (Op0I) {
2195 Value *A, *B;
2196 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2197 Op0I->hasOneUse()) {
2198 if (A == Op1) // (B|A)^B == (A|B)^B
2199 std::swap(A, B);
2200 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002201 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2203 Op0I->hasOneUse()){
2204 if (A == Op1) // (A&B)^A -> (B&A)^A
2205 std::swap(A, B);
2206 if (B == Op1 && // (B&A)^A == ~B & A
2207 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002208 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002209 }
2210 }
2211 }
2212
2213 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2214 if (Op0I && Op1I && Op0I->isShift() &&
2215 Op0I->getOpcode() == Op1I->getOpcode() &&
2216 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2217 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2218 Value *NewOp =
2219 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2220 Op0I->getName());
2221 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2222 Op1I->getOperand(1));
2223 }
2224
2225 if (Op0I && Op1I) {
2226 Value *A, *B, *C, *D;
2227 // (A & B)^(A | B) -> A ^ B
2228 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2229 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2230 if ((A == C && B == D) || (A == D && B == C))
2231 return BinaryOperator::CreateXor(A, B);
2232 }
2233 // (A | B)^(A & B) -> A ^ B
2234 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2235 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2236 if ((A == C && B == D) || (A == D && B == C))
2237 return BinaryOperator::CreateXor(A, B);
2238 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002239 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002240
Chris Lattner0a8191e2010-01-05 07:50:36 +00002241 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2242 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2243 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2244 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2245 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2246 LHS->getOperand(1) == RHS->getOperand(0))
2247 LHS->swapOperands();
2248 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2249 LHS->getOperand(1) == RHS->getOperand(1)) {
2250 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2251 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2252 bool isSigned = LHS->isSigned() || RHS->isSigned();
Chris Lattner067459c2010-03-05 08:46:26 +00002253 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002254 getNewICmpValue(isSigned, Code, Op0, Op1,
2255 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002256 }
2257 }
2258
2259 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2260 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2261 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2262 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002263 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002264 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002265 // Only do this if the casts both really cause code to be generated.
Chris Lattner4e8137d2010-02-11 06:26:33 +00002266 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2267 I.getType()) &&
2268 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2269 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002270 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2271 Op1C->getOperand(0), I.getName());
2272 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2273 }
2274 }
2275 }
2276
2277 return Changed ? &I : 0;
2278}