1
//===- InstCombineAndOrXor.cpp --------------------------------------------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This file implements the visitAnd, visitOr, and visitXor functions.
12
//===----------------------------------------------------------------------===//
14
#include "InstCombine.h"
15
#include "llvm/Intrinsics.h"
16
#include "llvm/Analysis/InstructionSimplify.h"
17
#include "llvm/Support/PatternMatch.h"
19
using namespace PatternMatch;
22
/// AddOne - Add one to a ConstantInt.
23
static Constant *AddOne(Constant *C) {
24
return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
26
/// SubOne - Subtract one from a ConstantInt.
27
static Constant *SubOne(ConstantInt *C) {
28
return ConstantInt::get(C->getContext(), C->getValue()-1);
31
/// isFreeToInvert - Return true if the specified value is free to invert (apply
32
/// ~ to). This happens in cases where the ~ can be eliminated.
33
static inline bool isFreeToInvert(Value *V) {
35
if (BinaryOperator::isNot(V))
38
// Constants can be considered to be not'ed values.
39
if (isa<ConstantInt>(V))
42
// Compares can be inverted if they have a single use.
43
if (CmpInst *CI = dyn_cast<CmpInst>(V))
44
return CI->hasOneUse();
49
static inline Value *dyn_castNotVal(Value *V) {
50
// If this is not(not(x)) don't return that this is a not: we want the two
51
// not's to be folded first.
52
if (BinaryOperator::isNot(V)) {
53
Value *Operand = BinaryOperator::getNotArgument(V);
54
if (!isFreeToInvert(Operand))
58
// Constants can be considered to be not'ed values...
59
if (ConstantInt *C = dyn_cast<ConstantInt>(V))
60
return ConstantInt::get(C->getType(), ~C->getValue());
65
/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
66
/// are carefully arranged to allow folding of expressions such as:
68
/// (A < B) | (A > B) --> (A != B)
70
/// Note that this is only valid if the first and second predicates have the
71
/// same sign. Is illegal to do: (A u< B) | (A s> B)
73
/// Three bits are used to represent the condition, as follows:
78
/// <=> Value Definition
79
/// 000 0 Always false
88
static unsigned getICmpCode(const ICmpInst *ICI) {
89
switch (ICI->getPredicate()) {
91
case ICmpInst::ICMP_UGT: return 1; // 001
92
case ICmpInst::ICMP_SGT: return 1; // 001
93
case ICmpInst::ICMP_EQ: return 2; // 010
94
case ICmpInst::ICMP_UGE: return 3; // 011
95
case ICmpInst::ICMP_SGE: return 3; // 011
96
case ICmpInst::ICMP_ULT: return 4; // 100
97
case ICmpInst::ICMP_SLT: return 4; // 100
98
case ICmpInst::ICMP_NE: return 5; // 101
99
case ICmpInst::ICMP_ULE: return 6; // 110
100
case ICmpInst::ICMP_SLE: return 6; // 110
103
llvm_unreachable("Invalid ICmp predicate!");
108
/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
109
/// predicate into a three bit mask. It also returns whether it is an ordered
110
/// predicate by reference.
111
static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
114
case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
115
case FCmpInst::FCMP_UNO: return 0; // 000
116
case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
117
case FCmpInst::FCMP_UGT: return 1; // 001
118
case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
119
case FCmpInst::FCMP_UEQ: return 2; // 010
120
case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
121
case FCmpInst::FCMP_UGE: return 3; // 011
122
case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
123
case FCmpInst::FCMP_ULT: return 4; // 100
124
case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
125
case FCmpInst::FCMP_UNE: return 5; // 101
126
case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
127
case FCmpInst::FCMP_ULE: return 6; // 110
130
// Not expecting FCMP_FALSE and FCMP_TRUE;
131
llvm_unreachable("Unexpected FCmp predicate!");
136
/// getICmpValue - This is the complement of getICmpCode, which turns an
137
/// opcode and two operands into either a constant true or false, or a brand
138
/// new ICmp instruction. The sign is passed in to determine which kind
139
/// of predicate to use in the new icmp instruction.
140
static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
141
InstCombiner::BuilderTy *Builder) {
142
CmpInst::Predicate Pred;
144
default: assert(0 && "Illegal ICmp code!");
146
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
147
case 1: Pred = Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
148
case 2: Pred = ICmpInst::ICMP_EQ; break;
149
case 3: Pred = Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
150
case 4: Pred = Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
151
case 5: Pred = ICmpInst::ICMP_NE; break;
152
case 6: Pred = Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
154
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
156
return Builder->CreateICmp(Pred, LHS, RHS);
159
/// getFCmpValue - This is the complement of getFCmpCode, which turns an
160
/// opcode and two operands into either a FCmp instruction. isordered is passed
161
/// in to determine which kind of predicate to use in the new fcmp instruction.
162
static Value *getFCmpValue(bool isordered, unsigned code,
163
Value *LHS, Value *RHS,
164
InstCombiner::BuilderTy *Builder) {
165
CmpInst::Predicate Pred;
167
default: assert(0 && "Illegal FCmp code!");
168
case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
169
case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
170
case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
171
case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
172
case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
173
case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
174
case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
175
case 7: return ConstantInt::getTrue(LHS->getContext());
177
return Builder->CreateFCmp(Pred, LHS, RHS);
180
/// PredicatesFoldable - Return true if both predicates match sign or if at
181
/// least one of them is an equality comparison (which is signless).
182
static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
183
return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
184
(CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
185
(CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
188
// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
189
// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
190
// guaranteed to be a binary operator.
191
Instruction *InstCombiner::OptAndOp(Instruction *Op,
194
BinaryOperator &TheAnd) {
195
Value *X = Op->getOperand(0);
196
Constant *Together = 0;
198
Together = ConstantExpr::getAnd(AndRHS, OpRHS);
200
switch (Op->getOpcode()) {
201
case Instruction::Xor:
202
if (Op->hasOneUse()) {
203
// (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
204
Value *And = Builder->CreateAnd(X, AndRHS);
206
return BinaryOperator::CreateXor(And, Together);
209
case Instruction::Or:
210
if (Together == AndRHS) // (X | C) & C --> C
211
return ReplaceInstUsesWith(TheAnd, AndRHS);
213
if (Op->hasOneUse() && Together != OpRHS) {
214
// (X | C1) & C2 --> (X | (C1&C2)) & C2
215
Value *Or = Builder->CreateOr(X, Together);
217
return BinaryOperator::CreateAnd(Or, AndRHS);
220
case Instruction::Add:
221
if (Op->hasOneUse()) {
222
// Adding a one to a single bit bit-field should be turned into an XOR
223
// of the bit. First thing to check is to see if this AND is with a
224
// single bit constant.
225
const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
227
// If there is only one bit set.
228
if (AndRHSV.isPowerOf2()) {
229
// Ok, at this point, we know that we are masking the result of the
230
// ADD down to exactly one bit. If the constant we are adding has
231
// no bits set below this bit, then we can eliminate the ADD.
232
const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
234
// Check to see if any bits below the one bit set in AndRHSV are set.
235
if ((AddRHS & (AndRHSV-1)) == 0) {
236
// If not, the only thing that can effect the output of the AND is
237
// the bit specified by AndRHSV. If that bit is set, the effect of
238
// the XOR is to toggle the bit. If it is clear, then the ADD has
240
if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
241
TheAnd.setOperand(0, X);
244
// Pull the XOR out of the AND.
245
Value *NewAnd = Builder->CreateAnd(X, AndRHS);
246
NewAnd->takeName(Op);
247
return BinaryOperator::CreateXor(NewAnd, AndRHS);
254
case Instruction::Shl: {
255
// We know that the AND will not produce any of the bits shifted in, so if
256
// the anded constant includes them, clear them now!
258
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
259
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
260
APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
261
ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
262
AndRHS->getValue() & ShlMask);
264
if (CI->getValue() == ShlMask) {
265
// Masking out bits that the shift already masks
266
return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
267
} else if (CI != AndRHS) { // Reducing bits set in and.
268
TheAnd.setOperand(1, CI);
273
case Instruction::LShr: {
274
// We know that the AND will not produce any of the bits shifted in, so if
275
// the anded constant includes them, clear them now! This only applies to
276
// unsigned shifts, because a signed shr may bring in set bits!
278
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
279
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
280
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
281
ConstantInt *CI = ConstantInt::get(Op->getContext(),
282
AndRHS->getValue() & ShrMask);
284
if (CI->getValue() == ShrMask) {
285
// Masking out bits that the shift already masks.
286
return ReplaceInstUsesWith(TheAnd, Op);
287
} else if (CI != AndRHS) {
288
TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
293
case Instruction::AShr:
295
// See if this is shifting in some sign extension, then masking it out
297
if (Op->hasOneUse()) {
298
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
299
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
300
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
301
Constant *C = ConstantInt::get(Op->getContext(),
302
AndRHS->getValue() & ShrMask);
303
if (C == AndRHS) { // Masking out bits shifted in.
304
// (Val ashr C1) & C2 -> (Val lshr C1) & C2
305
// Make the argument unsigned.
306
Value *ShVal = Op->getOperand(0);
307
ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
308
return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
317
/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
318
/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
319
/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
320
/// whether to treat the V, Lo and HI as signed or not. IB is the location to
321
/// insert new instructions.
322
Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
323
bool isSigned, bool Inside) {
324
assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
325
ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
326
"Lo is not <= Hi in range emission code!");
329
if (Lo == Hi) // Trivially false.
330
return ConstantInt::getFalse(V->getContext());
332
// V >= Min && V < Hi --> V < Hi
333
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
334
ICmpInst::Predicate pred = (isSigned ?
335
ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
336
return Builder->CreateICmp(pred, V, Hi);
339
// Emit V-Lo <u Hi-Lo
340
Constant *NegLo = ConstantExpr::getNeg(Lo);
341
Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
342
Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
343
return Builder->CreateICmpULT(Add, UpperBound);
346
if (Lo == Hi) // Trivially true.
347
return ConstantInt::getTrue(V->getContext());
349
// V < Min || V >= Hi -> V > Hi-1
350
Hi = SubOne(cast<ConstantInt>(Hi));
351
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
352
ICmpInst::Predicate pred = (isSigned ?
353
ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
354
return Builder->CreateICmp(pred, V, Hi);
357
// Emit V-Lo >u Hi-1-Lo
358
// Note that Hi has already had one subtracted from it, above.
359
ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
360
Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
361
Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
362
return Builder->CreateICmpUGT(Add, LowerBound);
365
// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
366
// any number of 0s on either side. The 1s are allowed to wrap from LSB to
367
// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
368
// not, since all 1s are not contiguous.
369
static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
370
const APInt& V = Val->getValue();
371
uint32_t BitWidth = Val->getType()->getBitWidth();
372
if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
374
// look for the first zero bit after the run of ones
375
MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
376
// look for the first non-zero bit
377
ME = V.getActiveBits();
381
/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
382
/// where isSub determines whether the operator is a sub. If we can fold one of
383
/// the following xforms:
385
/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
386
/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
387
/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
389
/// return (A +/- B).
391
Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
392
ConstantInt *Mask, bool isSub,
394
Instruction *LHSI = dyn_cast<Instruction>(LHS);
395
if (!LHSI || LHSI->getNumOperands() != 2 ||
396
!isa<ConstantInt>(LHSI->getOperand(1))) return 0;
398
ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
400
switch (LHSI->getOpcode()) {
402
case Instruction::And:
403
if (ConstantExpr::getAnd(N, Mask) == Mask) {
404
// If the AndRHS is a power of two minus one (0+1+), this is simple.
405
if ((Mask->getValue().countLeadingZeros() +
406
Mask->getValue().countPopulation()) ==
407
Mask->getValue().getBitWidth())
410
// Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
411
// part, we don't need any explicit masks to take them out of A. If that
412
// is all N is, ignore it.
413
uint32_t MB = 0, ME = 0;
414
if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
415
uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
416
APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
417
if (MaskedValueIsZero(RHS, Mask))
422
case Instruction::Or:
423
case Instruction::Xor:
424
// If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
425
if ((Mask->getValue().countLeadingZeros() +
426
Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
427
&& ConstantExpr::getAnd(N, Mask)->isNullValue())
433
return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
434
return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
437
/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
438
Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
439
ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
441
// (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
442
if (PredicatesFoldable(LHSCC, RHSCC)) {
443
if (LHS->getOperand(0) == RHS->getOperand(1) &&
444
LHS->getOperand(1) == RHS->getOperand(0))
446
if (LHS->getOperand(0) == RHS->getOperand(0) &&
447
LHS->getOperand(1) == RHS->getOperand(1)) {
448
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
449
unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
450
bool isSigned = LHS->isSigned() || RHS->isSigned();
451
return getICmpValue(isSigned, Code, Op0, Op1, Builder);
455
// This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
456
Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
457
ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
458
ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
459
if (LHSCst == 0 || RHSCst == 0) return 0;
461
if (LHSCst == RHSCst && LHSCC == RHSCC) {
462
// (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
463
// where C is a power of 2
464
if (LHSCC == ICmpInst::ICMP_ULT &&
465
LHSCst->getValue().isPowerOf2()) {
466
Value *NewOr = Builder->CreateOr(Val, Val2);
467
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
470
// (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
471
if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
472
Value *NewOr = Builder->CreateOr(Val, Val2);
473
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
477
// From here on, we only handle:
478
// (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
479
if (Val != Val2) return 0;
481
// ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
482
if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
483
RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
484
LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
485
RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
488
// We can't fold (ugt x, C) & (sgt x, C2).
489
if (!PredicatesFoldable(LHSCC, RHSCC))
492
// Ensure that the larger constant is on the RHS.
494
if (CmpInst::isSigned(LHSCC) ||
495
(ICmpInst::isEquality(LHSCC) &&
496
CmpInst::isSigned(RHSCC)))
497
ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
499
ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
503
std::swap(LHSCst, RHSCst);
504
std::swap(LHSCC, RHSCC);
507
// At this point, we know we have two icmp instructions
508
// comparing a value against two constants and and'ing the result
509
// together. Because of the above check, we know that we only have
510
// icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
511
// (from the icmp folding check above), that the two constants
512
// are not equal and that the larger constant is on the RHS
513
assert(LHSCst != RHSCst && "Compares not folded above?");
516
default: llvm_unreachable("Unknown integer condition code!");
517
case ICmpInst::ICMP_EQ:
519
default: llvm_unreachable("Unknown integer condition code!");
520
case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
521
case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
522
case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
523
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
524
case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
525
case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
526
case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
529
case ICmpInst::ICMP_NE:
531
default: llvm_unreachable("Unknown integer condition code!");
532
case ICmpInst::ICMP_ULT:
533
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
534
return Builder->CreateICmpULT(Val, LHSCst);
535
break; // (X != 13 & X u< 15) -> no change
536
case ICmpInst::ICMP_SLT:
537
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
538
return Builder->CreateICmpSLT(Val, LHSCst);
539
break; // (X != 13 & X s< 15) -> no change
540
case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
541
case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
542
case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
544
case ICmpInst::ICMP_NE:
545
if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
546
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
547
Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
548
return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
550
break; // (X != 13 & X != 15) -> no change
553
case ICmpInst::ICMP_ULT:
555
default: llvm_unreachable("Unknown integer condition code!");
556
case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
557
case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
558
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
559
case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
561
case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
562
case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
564
case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
568
case ICmpInst::ICMP_SLT:
570
default: llvm_unreachable("Unknown integer condition code!");
571
case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
572
case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
573
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
574
case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
576
case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
577
case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
579
case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
583
case ICmpInst::ICMP_UGT:
585
default: llvm_unreachable("Unknown integer condition code!");
586
case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
587
case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
589
case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
591
case ICmpInst::ICMP_NE:
592
if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
593
return Builder->CreateICmp(LHSCC, Val, RHSCst);
594
break; // (X u> 13 & X != 15) -> no change
595
case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
596
return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
597
case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
601
case ICmpInst::ICMP_SGT:
603
default: llvm_unreachable("Unknown integer condition code!");
604
case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
605
case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
607
case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
609
case ICmpInst::ICMP_NE:
610
if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
611
return Builder->CreateICmp(LHSCC, Val, RHSCst);
612
break; // (X s> 13 & X != 15) -> no change
613
case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
614
return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
615
case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
624
/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
625
/// instcombine, this returns a Value which should already be inserted into the
627
Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
628
if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
629
RHS->getPredicate() == FCmpInst::FCMP_ORD) {
630
// (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
631
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
632
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
633
// If either of the constants are nans, then the whole thing returns
635
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
636
return ConstantInt::getFalse(LHS->getContext());
637
return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
640
// Handle vector zeros. This occurs because the canonical form of
641
// "fcmp ord x,x" is "fcmp ord x, 0".
642
if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
643
isa<ConstantAggregateZero>(RHS->getOperand(1)))
644
return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
648
Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
649
Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
650
FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
653
if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
654
// Swap RHS operands to match LHS.
655
Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
656
std::swap(Op1LHS, Op1RHS);
659
if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
660
// Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
662
return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
663
if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
664
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
665
if (Op0CC == FCmpInst::FCMP_TRUE)
667
if (Op1CC == FCmpInst::FCMP_TRUE)
672
unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
673
unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
676
std::swap(Op0Pred, Op1Pred);
677
std::swap(Op0Ordered, Op1Ordered);
680
// uno && ueq -> uno && (uno || eq) -> ueq
681
// ord && olt -> ord && (ord && lt) -> olt
682
if (Op0Ordered == Op1Ordered)
685
// uno && oeq -> uno && (ord && eq) -> false
686
// uno && ord -> false
688
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
689
// ord && ueq -> ord && (uno || eq) -> oeq
690
return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
698
Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
699
bool Changed = SimplifyCommutative(I);
700
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
702
if (Value *V = SimplifyAndInst(Op0, Op1, TD))
703
return ReplaceInstUsesWith(I, V);
705
// See if we can simplify any instructions used by the instruction whose sole
706
// purpose is to compute bits we don't care about.
707
if (SimplifyDemandedInstructionBits(I))
710
if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
711
const APInt &AndRHSMask = AndRHS->getValue();
712
APInt NotAndRHS(~AndRHSMask);
714
// Optimize a variety of ((val OP C1) & C2) combinations...
715
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
716
Value *Op0LHS = Op0I->getOperand(0);
717
Value *Op0RHS = Op0I->getOperand(1);
718
switch (Op0I->getOpcode()) {
720
case Instruction::Xor:
721
case Instruction::Or:
722
// If the mask is only needed on one incoming arm, push it up.
723
if (!Op0I->hasOneUse()) break;
725
if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
726
// Not masking anything out for the LHS, move to RHS.
727
Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
728
Op0RHS->getName()+".masked");
729
return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
731
if (!isa<Constant>(Op0RHS) &&
732
MaskedValueIsZero(Op0RHS, NotAndRHS)) {
733
// Not masking anything out for the RHS, move to LHS.
734
Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
735
Op0LHS->getName()+".masked");
736
return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
740
case Instruction::Add:
741
// ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
742
// ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
743
// ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
744
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
745
return BinaryOperator::CreateAnd(V, AndRHS);
746
if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
747
return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
750
case Instruction::Sub:
751
// ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
752
// ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
753
// ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
754
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
755
return BinaryOperator::CreateAnd(V, AndRHS);
757
// (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
758
// has 1's for all bits that the subtraction with A might affect.
759
if (Op0I->hasOneUse()) {
760
uint32_t BitWidth = AndRHSMask.getBitWidth();
761
uint32_t Zeros = AndRHSMask.countLeadingZeros();
762
APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
764
ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
765
if (!(A && A->isZero()) && // avoid infinite recursion.
766
MaskedValueIsZero(Op0LHS, Mask)) {
767
Value *NewNeg = Builder->CreateNeg(Op0RHS);
768
return BinaryOperator::CreateAnd(NewNeg, AndRHS);
773
case Instruction::Shl:
774
case Instruction::LShr:
775
// (1 << x) & 1 --> zext(x == 0)
776
// (1 >> x) & 1 --> zext(x == 0)
777
if (AndRHSMask == 1 && Op0LHS == AndRHS) {
779
Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
780
return new ZExtInst(NewICmp, I.getType());
785
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
786
if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
788
} else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
789
// If this is an integer truncation or change from signed-to-unsigned, and
790
// if the source is an and/or with immediate, transform it. This
791
// frequently occurs for bitfield accesses.
792
if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
793
if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
794
CastOp->getNumOperands() == 2)
795
if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
796
if (CastOp->getOpcode() == Instruction::And) {
797
// Change: and (cast (and X, C1) to T), C2
798
// into : and (cast X to T), trunc_or_bitcast(C1)&C2
799
// This will fold the two constants together, which may allow
800
// other simplifications.
801
Value *NewCast = Builder->CreateTruncOrBitCast(
802
CastOp->getOperand(0), I.getType(),
803
CastOp->getName()+".shrunk");
804
// trunc_or_bitcast(C1)&C2
805
Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
806
C3 = ConstantExpr::getAnd(C3, AndRHS);
807
return BinaryOperator::CreateAnd(NewCast, C3);
808
} else if (CastOp->getOpcode() == Instruction::Or) {
809
// Change: and (cast (or X, C1) to T), C2
810
// into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
811
Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
812
if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
814
return ReplaceInstUsesWith(I, AndRHS);
820
// Try to fold constant and into select arguments.
821
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
822
if (Instruction *R = FoldOpIntoSelect(I, SI))
824
if (isa<PHINode>(Op0))
825
if (Instruction *NV = FoldOpIntoPhi(I))
830
// (~A & ~B) == (~(A | B)) - De Morgan's Law
831
if (Value *Op0NotVal = dyn_castNotVal(Op0))
832
if (Value *Op1NotVal = dyn_castNotVal(Op1))
833
if (Op0->hasOneUse() && Op1->hasOneUse()) {
834
Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
835
I.getName()+".demorgan");
836
return BinaryOperator::CreateNot(Or);
840
Value *A = 0, *B = 0, *C = 0, *D = 0;
841
// (A|B) & ~(A&B) -> A^B
842
if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
843
match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
844
((A == C && B == D) || (A == D && B == C)))
845
return BinaryOperator::CreateXor(A, B);
847
// ~(A&B) & (A|B) -> A^B
848
if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
849
match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
850
((A == C && B == D) || (A == D && B == C)))
851
return BinaryOperator::CreateXor(A, B);
853
if (Op0->hasOneUse() &&
854
match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
855
if (A == Op1) { // (A^B)&A -> A&(A^B)
856
I.swapOperands(); // Simplify below
858
} else if (B == Op1) { // (A^B)&B -> B&(B^A)
859
cast<BinaryOperator>(Op0)->swapOperands();
860
I.swapOperands(); // Simplify below
865
if (Op1->hasOneUse() &&
866
match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
867
if (B == Op0) { // B&(A^B) -> B&(B^A)
868
cast<BinaryOperator>(Op1)->swapOperands();
871
if (A == Op0) // A&(A^B) -> A & ~B
872
return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
875
// (A&((~A)|B)) -> A&B
876
if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
877
match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
878
return BinaryOperator::CreateAnd(A, Op1);
879
if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
880
match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
881
return BinaryOperator::CreateAnd(A, Op0);
884
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
885
if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
886
if (Value *Res = FoldAndOfICmps(LHS, RHS))
887
return ReplaceInstUsesWith(I, Res);
889
// If and'ing two fcmp, try combine them into one.
890
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
891
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
892
if (Value *Res = FoldAndOfFCmps(LHS, RHS))
893
return ReplaceInstUsesWith(I, Res);
896
// fold (and (cast A), (cast B)) -> (cast (and A, B))
897
if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
898
if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
899
const Type *SrcTy = Op0C->getOperand(0)->getType();
900
if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
901
SrcTy == Op1C->getOperand(0)->getType() &&
902
SrcTy->isIntOrIntVectorTy()) {
903
Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
905
// Only do this if the casts both really cause code to be generated.
906
if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
907
ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
908
Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
909
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
912
// If this is and(cast(icmp), cast(icmp)), try to fold this even if the
913
// cast is otherwise not optimizable. This happens for vector sexts.
914
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
915
if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
916
if (Value *Res = FoldAndOfICmps(LHS, RHS))
917
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
919
// If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
920
// cast is otherwise not optimizable. This happens for vector sexts.
921
if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
922
if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
923
if (Value *Res = FoldAndOfFCmps(LHS, RHS))
924
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
928
// (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
929
if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
930
if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
931
if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
932
SI0->getOperand(1) == SI1->getOperand(1) &&
933
(SI0->hasOneUse() || SI1->hasOneUse())) {
935
Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
937
return BinaryOperator::Create(SI1->getOpcode(), NewOp,
942
return Changed ? &I : 0;
945
/// CollectBSwapParts - Analyze the specified subexpression and see if it is
946
/// capable of providing pieces of a bswap. The subexpression provides pieces
947
/// of a bswap if it is proven that each of the non-zero bytes in the output of
948
/// the expression came from the corresponding "byte swapped" byte in some other
949
/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
950
/// we know that the expression deposits the low byte of %X into the high byte
951
/// of the bswap result and that all other bytes are zero. This expression is
952
/// accepted, the high byte of ByteValues is set to X to indicate a correct
955
/// This function returns true if the match was unsuccessful and false if so.
956
/// On entry to the function the "OverallLeftShift" is a signed integer value
957
/// indicating the number of bytes that the subexpression is later shifted. For
958
/// example, if the expression is later right shifted by 16 bits, the
959
/// OverallLeftShift value would be -2 on entry. This is used to specify which
960
/// byte of ByteValues is actually being set.
962
/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
963
/// byte is masked to zero by a user. For example, in (X & 255), X will be
964
/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
965
/// this function to working on up to 32-byte (256 bit) values. ByteMask is
966
/// always in the local (OverallLeftShift) coordinate space.
968
static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
969
SmallVector<Value*, 8> &ByteValues) {
970
if (Instruction *I = dyn_cast<Instruction>(V)) {
971
// If this is an or instruction, it may be an inner node of the bswap.
972
if (I->getOpcode() == Instruction::Or) {
973
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
975
CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
979
// If this is a logical shift by a constant multiple of 8, recurse with
980
// OverallLeftShift and ByteMask adjusted.
981
if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
983
cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
984
// Ensure the shift amount is defined and of a byte value.
985
if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
988
unsigned ByteShift = ShAmt >> 3;
989
if (I->getOpcode() == Instruction::Shl) {
990
// X << 2 -> collect(X, +2)
991
OverallLeftShift += ByteShift;
992
ByteMask >>= ByteShift;
994
// X >>u 2 -> collect(X, -2)
995
OverallLeftShift -= ByteShift;
996
ByteMask <<= ByteShift;
997
ByteMask &= (~0U >> (32-ByteValues.size()));
1000
if (OverallLeftShift >= (int)ByteValues.size()) return true;
1001
if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1003
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1007
// If this is a logical 'and' with a mask that clears bytes, clear the
1008
// corresponding bytes in ByteMask.
1009
if (I->getOpcode() == Instruction::And &&
1010
isa<ConstantInt>(I->getOperand(1))) {
1011
// Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1012
unsigned NumBytes = ByteValues.size();
1013
APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1014
const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1016
for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1017
// If this byte is masked out by a later operation, we don't care what
1019
if ((ByteMask & (1 << i)) == 0)
1022
// If the AndMask is all zeros for this byte, clear the bit.
1023
APInt MaskB = AndMask & Byte;
1025
ByteMask &= ~(1U << i);
1029
// If the AndMask is not all ones for this byte, it's not a bytezap.
1033
// Otherwise, this byte is kept.
1036
return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1041
// Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1042
// the input value to the bswap. Some observations: 1) if more than one byte
1043
// is demanded from this input, then it could not be successfully assembled
1044
// into a byteswap. At least one of the two bytes would not be aligned with
1045
// their ultimate destination.
1046
if (!isPowerOf2_32(ByteMask)) return true;
1047
unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1049
// 2) The input and ultimate destinations must line up: if byte 3 of an i32
1050
// is demanded, it needs to go into byte 0 of the result. This means that the
1051
// byte needs to be shifted until it lands in the right byte bucket. The
1052
// shift amount depends on the position: if the byte is coming from the high
1053
// part of the value (e.g. byte 3) then it must be shifted right. If from the
1054
// low part, it must be shifted left.
1055
unsigned DestByteNo = InputByteNo + OverallLeftShift;
1056
if (InputByteNo < ByteValues.size()/2) {
1057
if (ByteValues.size()-1-DestByteNo != InputByteNo)
1060
if (ByteValues.size()-1-DestByteNo != InputByteNo)
1064
// If the destination byte value is already defined, the values are or'd
1065
// together, which isn't a bswap (unless it's an or of the same bits).
1066
if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1068
ByteValues[DestByteNo] = V;
1072
/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1073
/// If so, insert the new bswap intrinsic and return it.
1074
Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1075
const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1076
if (!ITy || ITy->getBitWidth() % 16 ||
1077
// ByteMask only allows up to 32-byte values.
1078
ITy->getBitWidth() > 32*8)
1079
return 0; // Can only bswap pairs of bytes. Can't do vectors.
1081
/// ByteValues - For each byte of the result, we keep track of which value
1082
/// defines each byte.
1083
SmallVector<Value*, 8> ByteValues;
1084
ByteValues.resize(ITy->getBitWidth()/8);
1086
// Try to find all the pieces corresponding to the bswap.
1087
uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1088
if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1091
// Check to see if all of the bytes come from the same value.
1092
Value *V = ByteValues[0];
1093
if (V == 0) return 0; // Didn't find a byte? Must be zero.
1095
// Check to make sure that all of the bytes come from the same value.
1096
for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1097
if (ByteValues[i] != V)
1099
const Type *Tys[] = { ITy };
1100
Module *M = I.getParent()->getParent()->getParent();
1101
Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1102
return CallInst::Create(F, V);
1105
/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1106
/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1107
/// we can simplify this expression to "cond ? C : D or B".
1108
static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1109
Value *C, Value *D) {
1110
// If A is not a select of -1/0, this cannot match.
1112
if (!match(A, m_SExt(m_Value(Cond))) ||
1113
!Cond->getType()->isIntegerTy(1))
1116
// ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1117
if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1118
return SelectInst::Create(Cond, C, B);
1119
if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1120
return SelectInst::Create(Cond, C, B);
1122
// ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1123
if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1124
return SelectInst::Create(Cond, C, D);
1125
if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1126
return SelectInst::Create(Cond, C, D);
1130
/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1131
Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1132
ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1134
// (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1135
if (PredicatesFoldable(LHSCC, RHSCC)) {
1136
if (LHS->getOperand(0) == RHS->getOperand(1) &&
1137
LHS->getOperand(1) == RHS->getOperand(0))
1138
LHS->swapOperands();
1139
if (LHS->getOperand(0) == RHS->getOperand(0) &&
1140
LHS->getOperand(1) == RHS->getOperand(1)) {
1141
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1142
unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1143
bool isSigned = LHS->isSigned() || RHS->isSigned();
1144
return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1148
// This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1149
Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1150
ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1151
ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1152
if (LHSCst == 0 || RHSCst == 0) return 0;
1154
// (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1155
if (LHSCst == RHSCst && LHSCC == RHSCC &&
1156
LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1157
Value *NewOr = Builder->CreateOr(Val, Val2);
1158
return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1161
// From here on, we only handle:
1162
// (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1163
if (Val != Val2) return 0;
1165
// ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1166
if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1167
RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1168
LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1169
RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1172
// We can't fold (ugt x, C) | (sgt x, C2).
1173
if (!PredicatesFoldable(LHSCC, RHSCC))
1176
// Ensure that the larger constant is on the RHS.
1178
if (CmpInst::isSigned(LHSCC) ||
1179
(ICmpInst::isEquality(LHSCC) &&
1180
CmpInst::isSigned(RHSCC)))
1181
ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1183
ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1186
std::swap(LHS, RHS);
1187
std::swap(LHSCst, RHSCst);
1188
std::swap(LHSCC, RHSCC);
1191
// At this point, we know we have two icmp instructions
1192
// comparing a value against two constants and or'ing the result
1193
// together. Because of the above check, we know that we only have
1194
// ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1195
// icmp folding check above), that the two constants are not
1197
assert(LHSCst != RHSCst && "Compares not folded above?");
1200
default: llvm_unreachable("Unknown integer condition code!");
1201
case ICmpInst::ICMP_EQ:
1203
default: llvm_unreachable("Unknown integer condition code!");
1204
case ICmpInst::ICMP_EQ:
1205
if (LHSCst == SubOne(RHSCst)) {
1206
// (X == 13 | X == 14) -> X-13 <u 2
1207
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1208
Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1209
AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1210
return Builder->CreateICmpULT(Add, AddCST);
1212
break; // (X == 13 | X == 15) -> no change
1213
case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1214
case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1216
case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1217
case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1218
case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1222
case ICmpInst::ICMP_NE:
1224
default: llvm_unreachable("Unknown integer condition code!");
1225
case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1226
case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1227
case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1229
case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1230
case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1231
case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1232
return ConstantInt::getTrue(LHS->getContext());
1235
case ICmpInst::ICMP_ULT:
1237
default: llvm_unreachable("Unknown integer condition code!");
1238
case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1240
case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1241
// If RHSCst is [us]MAXINT, it is always false. Not handling
1242
// this can cause overflow.
1243
if (RHSCst->isMaxValue(false))
1245
return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1246
case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1248
case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1249
case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1251
case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1255
case ICmpInst::ICMP_SLT:
1257
default: llvm_unreachable("Unknown integer condition code!");
1258
case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1260
case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1261
// If RHSCst is [us]MAXINT, it is always false. Not handling
1262
// this can cause overflow.
1263
if (RHSCst->isMaxValue(true))
1265
return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1266
case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1268
case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1269
case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1271
case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1275
case ICmpInst::ICMP_UGT:
1277
default: llvm_unreachable("Unknown integer condition code!");
1278
case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1279
case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1281
case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1283
case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1284
case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1285
return ConstantInt::getTrue(LHS->getContext());
1286
case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1290
case ICmpInst::ICMP_SGT:
1292
default: llvm_unreachable("Unknown integer condition code!");
1293
case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1294
case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1296
case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1298
case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1299
case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1300
return ConstantInt::getTrue(LHS->getContext());
1301
case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1309
/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1310
/// instcombine, this returns a Value which should already be inserted into the
1312
Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1313
if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1314
RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1315
LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1316
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1317
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1318
// If either of the constants are nans, then the whole thing returns
1320
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1321
return ConstantInt::getTrue(LHS->getContext());
1323
// Otherwise, no need to compare the two constants, compare the
1325
return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1328
// Handle vector zeros. This occurs because the canonical form of
1329
// "fcmp uno x,x" is "fcmp uno x, 0".
1330
if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1331
isa<ConstantAggregateZero>(RHS->getOperand(1)))
1332
return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1337
Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1338
Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1339
FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1341
if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1342
// Swap RHS operands to match LHS.
1343
Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1344
std::swap(Op1LHS, Op1RHS);
1346
if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1347
// Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1349
return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1350
if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1351
return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1352
if (Op0CC == FCmpInst::FCMP_FALSE)
1354
if (Op1CC == FCmpInst::FCMP_FALSE)
1358
unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1359
unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1360
if (Op0Ordered == Op1Ordered) {
1361
// If both are ordered or unordered, return a new fcmp with
1362
// or'ed predicates.
1363
return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1369
/// FoldOrWithConstants - This helper function folds:
1371
/// ((A | B) & C1) | (B & C2)
1377
/// when the XOR of the two constants is "all ones" (-1).
1378
Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1379
Value *A, Value *B, Value *C) {
1380
ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1384
ConstantInt *CI2 = 0;
1385
if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1387
APInt Xor = CI1->getValue() ^ CI2->getValue();
1388
if (!Xor.isAllOnesValue()) return 0;
1390
if (V1 == A || V1 == B) {
1391
Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1392
return BinaryOperator::CreateOr(NewOp, V1);
1398
Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1399
bool Changed = SimplifyCommutative(I);
1400
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1402
if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1403
return ReplaceInstUsesWith(I, V);
1405
// See if we can simplify any instructions used by the instruction whose sole
1406
// purpose is to compute bits we don't care about.
1407
if (SimplifyDemandedInstructionBits(I))
1410
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1411
ConstantInt *C1 = 0; Value *X = 0;
1412
// (X & C1) | C2 --> (X | C2) & (C1|C2)
1413
// iff (C1 & C2) == 0.
1414
if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1415
(RHS->getValue() & C1->getValue()) != 0 &&
1417
Value *Or = Builder->CreateOr(X, RHS);
1419
return BinaryOperator::CreateAnd(Or,
1420
ConstantInt::get(I.getContext(),
1421
RHS->getValue() | C1->getValue()));
1424
// (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1425
if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1427
Value *Or = Builder->CreateOr(X, RHS);
1429
return BinaryOperator::CreateXor(Or,
1430
ConstantInt::get(I.getContext(),
1431
C1->getValue() & ~RHS->getValue()));
1434
// Try to fold constant and into select arguments.
1435
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1436
if (Instruction *R = FoldOpIntoSelect(I, SI))
1439
if (isa<PHINode>(Op0))
1440
if (Instruction *NV = FoldOpIntoPhi(I))
1444
Value *A = 0, *B = 0;
1445
ConstantInt *C1 = 0, *C2 = 0;
1447
// (A | B) | C and A | (B | C) -> bswap if possible.
1448
// (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1449
if (match(Op0, m_Or(m_Value(), m_Value())) ||
1450
match(Op1, m_Or(m_Value(), m_Value())) ||
1451
(match(Op0, m_Shift(m_Value(), m_Value())) &&
1452
match(Op1, m_Shift(m_Value(), m_Value())))) {
1453
if (Instruction *BSwap = MatchBSwap(I))
1457
// (X^C)|Y -> (X|Y)^C iff Y&C == 0
1458
if (Op0->hasOneUse() &&
1459
match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1460
MaskedValueIsZero(Op1, C1->getValue())) {
1461
Value *NOr = Builder->CreateOr(A, Op1);
1463
return BinaryOperator::CreateXor(NOr, C1);
1466
// Y|(X^C) -> (X|Y)^C iff Y&C == 0
1467
if (Op1->hasOneUse() &&
1468
match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1469
MaskedValueIsZero(Op0, C1->getValue())) {
1470
Value *NOr = Builder->CreateOr(A, Op0);
1472
return BinaryOperator::CreateXor(NOr, C1);
1476
Value *C = 0, *D = 0;
1477
if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1478
match(Op1, m_And(m_Value(B), m_Value(D)))) {
1479
Value *V1 = 0, *V2 = 0, *V3 = 0;
1480
C1 = dyn_cast<ConstantInt>(C);
1481
C2 = dyn_cast<ConstantInt>(D);
1482
if (C1 && C2) { // (A & C1)|(B & C2)
1483
// If we have: ((V + N) & C1) | (V & C2)
1484
// .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1485
// replace with V+N.
1486
if (C1->getValue() == ~C2->getValue()) {
1487
if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1488
match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1489
// Add commutes, try both ways.
1490
if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1491
return ReplaceInstUsesWith(I, A);
1492
if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1493
return ReplaceInstUsesWith(I, A);
1495
// Or commutes, try both ways.
1496
if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1497
match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1498
// Add commutes, try both ways.
1499
if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1500
return ReplaceInstUsesWith(I, B);
1501
if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1502
return ReplaceInstUsesWith(I, B);
1506
if ((C1->getValue() & C2->getValue()) == 0) {
1507
// ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1508
// iff (C1&C2) == 0 and (N&~C1) == 0
1509
if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1510
((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1511
(V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1512
return BinaryOperator::CreateAnd(A,
1513
ConstantInt::get(A->getContext(),
1514
C1->getValue()|C2->getValue()));
1515
// Or commutes, try both ways.
1516
if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1517
((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1518
(V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1519
return BinaryOperator::CreateAnd(B,
1520
ConstantInt::get(B->getContext(),
1521
C1->getValue()|C2->getValue()));
1523
// ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1524
// iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1525
ConstantInt *C3 = 0, *C4 = 0;
1526
if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1527
(C3->getValue() & ~C1->getValue()) == 0 &&
1528
match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1529
(C4->getValue() & ~C2->getValue()) == 0) {
1530
V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1531
return BinaryOperator::CreateAnd(V2,
1532
ConstantInt::get(B->getContext(),
1533
C1->getValue()|C2->getValue()));
1538
// Check to see if we have any common things being and'ed. If so, find the
1539
// terms for V1 & (V2|V3).
1540
if (Op0->hasOneUse() || Op1->hasOneUse()) {
1542
if (A == B) // (A & C)|(A & D) == A & (C|D)
1543
V1 = A, V2 = C, V3 = D;
1544
else if (A == D) // (A & C)|(B & A) == A & (B|C)
1545
V1 = A, V2 = B, V3 = C;
1546
else if (C == B) // (A & C)|(C & D) == C & (A|D)
1547
V1 = C, V2 = A, V3 = D;
1548
else if (C == D) // (A & C)|(B & C) == C & (A|B)
1549
V1 = C, V2 = A, V3 = B;
1552
Value *Or = Builder->CreateOr(V2, V3, "tmp");
1553
return BinaryOperator::CreateAnd(V1, Or);
1557
// (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1558
// Don't do this for vector select idioms, the code generator doesn't handle
1560
if (!I.getType()->isVectorTy()) {
1561
if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1563
if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1565
if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1567
if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1571
// ((A&~B)|(~A&B)) -> A^B
1572
if ((match(C, m_Not(m_Specific(D))) &&
1573
match(B, m_Not(m_Specific(A)))))
1574
return BinaryOperator::CreateXor(A, D);
1575
// ((~B&A)|(~A&B)) -> A^B
1576
if ((match(A, m_Not(m_Specific(D))) &&
1577
match(B, m_Not(m_Specific(C)))))
1578
return BinaryOperator::CreateXor(C, D);
1579
// ((A&~B)|(B&~A)) -> A^B
1580
if ((match(C, m_Not(m_Specific(B))) &&
1581
match(D, m_Not(m_Specific(A)))))
1582
return BinaryOperator::CreateXor(A, B);
1583
// ((~B&A)|(B&~A)) -> A^B
1584
if ((match(A, m_Not(m_Specific(B))) &&
1585
match(D, m_Not(m_Specific(C)))))
1586
return BinaryOperator::CreateXor(C, B);
1589
// (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1590
if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1591
if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1592
if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1593
SI0->getOperand(1) == SI1->getOperand(1) &&
1594
(SI0->hasOneUse() || SI1->hasOneUse())) {
1595
Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1597
return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1598
SI1->getOperand(1));
1602
// ((A|B)&1)|(B&-2) -> (A&1) | B
1603
if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1604
match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1605
Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
1606
if (Ret) return Ret;
1608
// (B&-2)|((A|B)&1) -> (A&1) | B
1609
if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1610
match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1611
Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
1612
if (Ret) return Ret;
1615
// (~A | ~B) == (~(A & B)) - De Morgan's Law
1616
if (Value *Op0NotVal = dyn_castNotVal(Op0))
1617
if (Value *Op1NotVal = dyn_castNotVal(Op1))
1618
if (Op0->hasOneUse() && Op1->hasOneUse()) {
1619
Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1620
I.getName()+".demorgan");
1621
return BinaryOperator::CreateNot(And);
1624
if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1625
if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1626
if (Value *Res = FoldOrOfICmps(LHS, RHS))
1627
return ReplaceInstUsesWith(I, Res);
1629
// (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1630
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1631
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1632
if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1633
return ReplaceInstUsesWith(I, Res);
1635
// fold (or (cast A), (cast B)) -> (cast (or A, B))
1636
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1637
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1638
if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1639
const Type *SrcTy = Op0C->getOperand(0)->getType();
1640
if (SrcTy == Op1C->getOperand(0)->getType() &&
1641
SrcTy->isIntOrIntVectorTy()) {
1642
Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1644
if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1645
// Only do this if the casts both really cause code to be
1647
ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1648
ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1649
Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1650
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1653
// If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1654
// cast is otherwise not optimizable. This happens for vector sexts.
1655
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1656
if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1657
if (Value *Res = FoldOrOfICmps(LHS, RHS))
1658
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1660
// If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1661
// cast is otherwise not optimizable. This happens for vector sexts.
1662
if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1663
if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1664
if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1665
return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1670
return Changed ? &I : 0;
1673
Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1674
bool Changed = SimplifyCommutative(I);
1675
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1677
if (isa<UndefValue>(Op1)) {
1678
if (isa<UndefValue>(Op0))
1679
// Handle undef ^ undef -> 0 special case. This is a common
1681
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1682
return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1687
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1689
// See if we can simplify any instructions used by the instruction whose sole
1690
// purpose is to compute bits we don't care about.
1691
if (SimplifyDemandedInstructionBits(I))
1693
if (I.getType()->isVectorTy())
1694
if (isa<ConstantAggregateZero>(Op1))
1695
return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
1697
// Is this a ~ operation?
1698
if (Value *NotOp = dyn_castNotVal(&I)) {
1699
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1700
if (Op0I->getOpcode() == Instruction::And ||
1701
Op0I->getOpcode() == Instruction::Or) {
1702
// ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1703
// ~(~X | Y) === (X & ~Y) - De Morgan's Law
1704
if (dyn_castNotVal(Op0I->getOperand(1)))
1705
Op0I->swapOperands();
1706
if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1708
Builder->CreateNot(Op0I->getOperand(1),
1709
Op0I->getOperand(1)->getName()+".not");
1710
if (Op0I->getOpcode() == Instruction::And)
1711
return BinaryOperator::CreateOr(Op0NotVal, NotY);
1712
return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1715
// ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1716
// ~(X | Y) === (~X & ~Y) - De Morgan's Law
1717
if (isFreeToInvert(Op0I->getOperand(0)) &&
1718
isFreeToInvert(Op0I->getOperand(1))) {
1720
Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1722
Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1723
if (Op0I->getOpcode() == Instruction::And)
1724
return BinaryOperator::CreateOr(NotX, NotY);
1725
return BinaryOperator::CreateAnd(NotX, NotY);
1728
} else if (Op0I->getOpcode() == Instruction::AShr) {
1729
// ~(~X >>s Y) --> (X >>s Y)
1730
if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1731
return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1737
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1738
if (RHS->isOne() && Op0->hasOneUse()) {
1739
// xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1740
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
1741
return new ICmpInst(ICI->getInversePredicate(),
1742
ICI->getOperand(0), ICI->getOperand(1));
1744
if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
1745
return new FCmpInst(FCI->getInversePredicate(),
1746
FCI->getOperand(0), FCI->getOperand(1));
1749
// fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1750
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1751
if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1752
if (CI->hasOneUse() && Op0C->hasOneUse()) {
1753
Instruction::CastOps Opcode = Op0C->getOpcode();
1754
if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1755
(RHS == ConstantExpr::getCast(Opcode,
1756
ConstantInt::getTrue(I.getContext()),
1757
Op0C->getDestTy()))) {
1758
CI->setPredicate(CI->getInversePredicate());
1759
return CastInst::Create(Opcode, CI, Op0C->getType());
1765
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1766
// ~(c-X) == X-c-1 == X+(-c-1)
1767
if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1768
if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1769
Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1770
Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1771
ConstantInt::get(I.getType(), 1));
1772
return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1775
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1776
if (Op0I->getOpcode() == Instruction::Add) {
1777
// ~(X-c) --> (-c-1)-X
1778
if (RHS->isAllOnesValue()) {
1779
Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1780
return BinaryOperator::CreateSub(
1781
ConstantExpr::getSub(NegOp0CI,
1782
ConstantInt::get(I.getType(), 1)),
1783
Op0I->getOperand(0));
1784
} else if (RHS->getValue().isSignBit()) {
1785
// (X + C) ^ signbit -> (X + C + signbit)
1786
Constant *C = ConstantInt::get(I.getContext(),
1787
RHS->getValue() + Op0CI->getValue());
1788
return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1791
} else if (Op0I->getOpcode() == Instruction::Or) {
1792
// (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1793
if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1794
Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1795
// Anything in both C1 and C2 is known to be zero, remove it from
1797
Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1798
NewRHS = ConstantExpr::getAnd(NewRHS,
1799
ConstantExpr::getNot(CommonBits));
1801
I.setOperand(0, Op0I->getOperand(0));
1802
I.setOperand(1, NewRHS);
1809
// Try to fold constant and into select arguments.
1810
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1811
if (Instruction *R = FoldOpIntoSelect(I, SI))
1813
if (isa<PHINode>(Op0))
1814
if (Instruction *NV = FoldOpIntoPhi(I))
1818
if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1820
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1822
if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1824
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1827
BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1830
if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1831
if (A == Op0) { // B^(B|A) == (A|B)^B
1832
Op1I->swapOperands();
1834
std::swap(Op0, Op1);
1835
} else if (B == Op0) { // B^(A|B) == (A|B)^B
1836
I.swapOperands(); // Simplified below.
1837
std::swap(Op0, Op1);
1839
} else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1840
return ReplaceInstUsesWith(I, B); // A^(A^B) == B
1841
} else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1842
return ReplaceInstUsesWith(I, A); // A^(B^A) == B
1843
} else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
1845
if (A == Op0) { // A^(A&B) -> A^(B&A)
1846
Op1I->swapOperands();
1849
if (B == Op0) { // A^(B&A) -> (B&A)^A
1850
I.swapOperands(); // Simplified below.
1851
std::swap(Op0, Op1);
1856
BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1859
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1860
Op0I->hasOneUse()) {
1861
if (A == Op1) // (B|A)^B == (A|B)^B
1863
if (B == Op1) // (A|B)^B == A & ~B
1864
return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1865
} else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1866
return ReplaceInstUsesWith(I, B); // (A^B)^A == B
1867
} else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1868
return ReplaceInstUsesWith(I, A); // (B^A)^A == B
1869
} else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1871
if (A == Op1) // (A&B)^A -> (B&A)^A
1873
if (B == Op1 && // (B&A)^A == ~B & A
1874
!isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
1875
return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1880
// (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
1881
if (Op0I && Op1I && Op0I->isShift() &&
1882
Op0I->getOpcode() == Op1I->getOpcode() &&
1883
Op0I->getOperand(1) == Op1I->getOperand(1) &&
1884
(Op1I->hasOneUse() || Op1I->hasOneUse())) {
1886
Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1888
return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
1889
Op1I->getOperand(1));
1893
Value *A, *B, *C, *D;
1894
// (A & B)^(A | B) -> A ^ B
1895
if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1896
match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1897
if ((A == C && B == D) || (A == D && B == C))
1898
return BinaryOperator::CreateXor(A, B);
1900
// (A | B)^(A & B) -> A ^ B
1901
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1902
match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1903
if ((A == C && B == D) || (A == D && B == C))
1904
return BinaryOperator::CreateXor(A, B);
1908
if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1909
match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1910
match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1911
// (X & Y)^(X & Y) -> (Y^Z) & X
1912
Value *X = 0, *Y = 0, *Z = 0;
1914
X = A, Y = B, Z = D;
1916
X = A, Y = B, Z = C;
1918
X = B, Y = A, Z = D;
1920
X = B, Y = A, Z = C;
1923
Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1924
return BinaryOperator::CreateAnd(NewOp, X);
1929
// (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1930
if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1931
if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1932
if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1933
if (LHS->getOperand(0) == RHS->getOperand(1) &&
1934
LHS->getOperand(1) == RHS->getOperand(0))
1935
LHS->swapOperands();
1936
if (LHS->getOperand(0) == RHS->getOperand(0) &&
1937
LHS->getOperand(1) == RHS->getOperand(1)) {
1938
Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1939
unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1940
bool isSigned = LHS->isSigned() || RHS->isSigned();
1941
return ReplaceInstUsesWith(I,
1942
getICmpValue(isSigned, Code, Op0, Op1, Builder));
1946
// fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1947
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1948
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1949
if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1950
const Type *SrcTy = Op0C->getOperand(0)->getType();
1951
if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
1952
// Only do this if the casts both really cause code to be generated.
1953
ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
1955
ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
1957
Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1958
Op1C->getOperand(0), I.getName());
1959
return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1964
return Changed ? &I : 0;