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 "InstCombineInternal.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
21 using namespace PatternMatch;
23 #define DEBUG_TYPE "instcombine"
25 static inline Value *dyn_castNotVal(Value *V) {
26 // If this is not(not(x)) don't return that this is a not: we want the two
27 // not's to be folded first.
28 if (BinaryOperator::isNot(V)) {
29 Value *Operand = BinaryOperator::getNotArgument(V);
30 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
34 // Constants can be considered to be not'ed values...
35 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
36 return ConstantInt::get(C->getType(), ~C->getValue());
40 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
41 /// a three bit mask. It also returns whether it is an ordered predicate by
43 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
46 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
47 case FCmpInst::FCMP_UNO: return 0; // 000
48 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
49 case FCmpInst::FCMP_UGT: return 1; // 001
50 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
51 case FCmpInst::FCMP_UEQ: return 2; // 010
52 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
53 case FCmpInst::FCMP_UGE: return 3; // 011
54 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
55 case FCmpInst::FCMP_ULT: return 4; // 100
56 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
57 case FCmpInst::FCMP_UNE: return 5; // 101
58 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
59 case FCmpInst::FCMP_ULE: return 6; // 110
62 // Not expecting FCMP_FALSE and FCMP_TRUE;
63 llvm_unreachable("Unexpected FCmp predicate!");
67 /// This is the complement of getICmpCode, which turns an opcode and two
68 /// operands into either a constant true or false, or a brand new ICmp
69 /// instruction. The sign is passed in to determine which kind of predicate to
70 /// use in the new icmp instruction.
71 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
73 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
76 return Builder->CreateICmp(NewPred, LHS, RHS);
79 /// This is the complement of getFCmpCode, which turns an opcode and two
80 /// operands into either a FCmp instruction. isordered is passed in to determine
81 /// which kind of predicate to use in the new fcmp instruction.
82 static Value *getFCmpValue(bool isordered, unsigned code,
83 Value *LHS, Value *RHS,
84 InstCombiner::BuilderTy *Builder) {
85 CmpInst::Predicate Pred;
87 default: llvm_unreachable("Illegal FCmp code!");
88 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
89 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
90 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
91 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
92 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
93 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
94 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
97 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
98 Pred = FCmpInst::FCMP_ORD; break;
100 return Builder->CreateFCmp(Pred, LHS, RHS);
103 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
104 /// \param I Binary operator to transform.
105 /// \return Pointer to node that must replace the original binary operator, or
106 /// null pointer if no transformation was made.
107 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
108 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
111 if (I.getType()->isVectorTy()) return nullptr;
113 // Can only do bitwise ops.
114 unsigned Op = I.getOpcode();
115 if (Op != Instruction::And && Op != Instruction::Or &&
116 Op != Instruction::Xor)
119 Value *OldLHS = I.getOperand(0);
120 Value *OldRHS = I.getOperand(1);
121 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
122 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
123 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
124 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
125 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
126 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
128 if (!IsBswapLHS && !IsBswapRHS)
131 if (!IsBswapLHS && !ConstLHS)
134 if (!IsBswapRHS && !ConstRHS)
137 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
138 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
139 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
140 Builder->getInt(ConstLHS->getValue().byteSwap());
142 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
143 Builder->getInt(ConstRHS->getValue().byteSwap());
145 Value *BinOp = nullptr;
146 if (Op == Instruction::And)
147 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
148 else if (Op == Instruction::Or)
149 BinOp = Builder->CreateOr(NewLHS, NewRHS);
150 else //if (Op == Instruction::Xor)
151 BinOp = Builder->CreateXor(NewLHS, NewRHS);
153 Module *M = I.getParent()->getParent()->getParent();
154 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
155 return Builder->CreateCall(F, BinOp);
158 /// This handles expressions of the form ((val OP C1) & C2). Where
159 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
160 /// guaranteed to be a binary operator.
161 Instruction *InstCombiner::OptAndOp(Instruction *Op,
164 BinaryOperator &TheAnd) {
165 Value *X = Op->getOperand(0);
166 Constant *Together = nullptr;
168 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
170 switch (Op->getOpcode()) {
171 case Instruction::Xor:
172 if (Op->hasOneUse()) {
173 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
174 Value *And = Builder->CreateAnd(X, AndRHS);
176 return BinaryOperator::CreateXor(And, Together);
179 case Instruction::Or:
180 if (Op->hasOneUse()){
181 if (Together != OpRHS) {
182 // (X | C1) & C2 --> (X | (C1&C2)) & C2
183 Value *Or = Builder->CreateOr(X, Together);
185 return BinaryOperator::CreateAnd(Or, AndRHS);
188 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
189 if (TogetherCI && !TogetherCI->isZero()){
190 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
191 // NOTE: This reduces the number of bits set in the & mask, which
192 // can expose opportunities for store narrowing.
193 Together = ConstantExpr::getXor(AndRHS, Together);
194 Value *And = Builder->CreateAnd(X, Together);
196 return BinaryOperator::CreateOr(And, OpRHS);
201 case Instruction::Add:
202 if (Op->hasOneUse()) {
203 // Adding a one to a single bit bit-field should be turned into an XOR
204 // of the bit. First thing to check is to see if this AND is with a
205 // single bit constant.
206 const APInt &AndRHSV = AndRHS->getValue();
208 // If there is only one bit set.
209 if (AndRHSV.isPowerOf2()) {
210 // Ok, at this point, we know that we are masking the result of the
211 // ADD down to exactly one bit. If the constant we are adding has
212 // no bits set below this bit, then we can eliminate the ADD.
213 const APInt& AddRHS = OpRHS->getValue();
215 // Check to see if any bits below the one bit set in AndRHSV are set.
216 if ((AddRHS & (AndRHSV-1)) == 0) {
217 // If not, the only thing that can effect the output of the AND is
218 // the bit specified by AndRHSV. If that bit is set, the effect of
219 // the XOR is to toggle the bit. If it is clear, then the ADD has
221 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
222 TheAnd.setOperand(0, X);
225 // Pull the XOR out of the AND.
226 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
227 NewAnd->takeName(Op);
228 return BinaryOperator::CreateXor(NewAnd, AndRHS);
235 case Instruction::Shl: {
236 // We know that the AND will not produce any of the bits shifted in, so if
237 // the anded constant includes them, clear them now!
239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
242 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
244 if (CI->getValue() == ShlMask)
245 // Masking out bits that the shift already masks.
246 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
248 if (CI != AndRHS) { // Reducing bits set in and.
249 TheAnd.setOperand(1, CI);
254 case Instruction::LShr: {
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! This only applies to
257 // unsigned shifts, because a signed shr may bring in set bits!
259 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
260 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
261 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
262 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
264 if (CI->getValue() == ShrMask)
265 // Masking out bits that the shift already masks.
266 return ReplaceInstUsesWith(TheAnd, Op);
269 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
274 case Instruction::AShr:
276 // See if this is shifting in some sign extension, then masking it out
278 if (Op->hasOneUse()) {
279 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
280 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
281 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
282 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
283 if (C == AndRHS) { // Masking out bits shifted in.
284 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
285 // Make the argument unsigned.
286 Value *ShVal = Op->getOperand(0);
287 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
288 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
296 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
297 /// (V < Lo || V >= Hi). In practice, we emit the more efficient
298 /// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
299 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
300 /// insert new instructions.
301 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
302 bool isSigned, bool Inside) {
303 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
304 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
305 "Lo is not <= Hi in range emission code!");
308 if (Lo == Hi) // Trivially false.
309 return Builder->getFalse();
311 // V >= Min && V < Hi --> V < Hi
312 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
313 ICmpInst::Predicate pred = (isSigned ?
314 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
315 return Builder->CreateICmp(pred, V, Hi);
318 // Emit V-Lo <u Hi-Lo
319 Constant *NegLo = ConstantExpr::getNeg(Lo);
320 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
321 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
322 return Builder->CreateICmpULT(Add, UpperBound);
325 if (Lo == Hi) // Trivially true.
326 return Builder->getTrue();
328 // V < Min || V >= Hi -> V > Hi-1
329 Hi = SubOne(cast<ConstantInt>(Hi));
330 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
331 ICmpInst::Predicate pred = (isSigned ?
332 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
333 return Builder->CreateICmp(pred, V, Hi);
336 // Emit V-Lo >u Hi-1-Lo
337 // Note that Hi has already had one subtracted from it, above.
338 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
339 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
340 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
341 return Builder->CreateICmpUGT(Add, LowerBound);
344 /// Returns true iff Val consists of one contiguous run of 1s with any number
345 /// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
346 /// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
347 /// not, since all 1s are not contiguous.
348 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
349 const APInt& V = Val->getValue();
350 uint32_t BitWidth = Val->getType()->getBitWidth();
351 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
353 // look for the first zero bit after the run of ones
354 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
355 // look for the first non-zero bit
356 ME = V.getActiveBits();
360 /// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
361 /// whether the operator is a sub. If we can fold one of the following xforms:
363 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
364 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
367 /// return (A +/- B).
369 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
370 ConstantInt *Mask, bool isSub,
372 Instruction *LHSI = dyn_cast<Instruction>(LHS);
373 if (!LHSI || LHSI->getNumOperands() != 2 ||
374 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
376 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
378 switch (LHSI->getOpcode()) {
379 default: return nullptr;
380 case Instruction::And:
381 if (ConstantExpr::getAnd(N, Mask) == Mask) {
382 // If the AndRHS is a power of two minus one (0+1+), this is simple.
383 if ((Mask->getValue().countLeadingZeros() +
384 Mask->getValue().countPopulation()) ==
385 Mask->getValue().getBitWidth())
388 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
389 // part, we don't need any explicit masks to take them out of A. If that
390 // is all N is, ignore it.
391 uint32_t MB = 0, ME = 0;
392 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
393 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
394 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
395 if (MaskedValueIsZero(RHS, Mask, 0, &I))
400 case Instruction::Or:
401 case Instruction::Xor:
402 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
403 if ((Mask->getValue().countLeadingZeros() +
404 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
405 && ConstantExpr::getAnd(N, Mask)->isNullValue())
411 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
412 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
415 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
416 /// One of A and B is considered the mask, the other the value. This is
417 /// described as the "AMask" or "BMask" part of the enum. If the enum
418 /// contains only "Mask", then both A and B can be considered masks.
419 /// If A is the mask, then it was proven, that (A & C) == C. This
420 /// is trivial if C == A, or C == 0. If both A and C are constants, this
421 /// proof is also easy.
422 /// For the following explanations we assume that A is the mask.
423 /// The part "AllOnes" declares, that the comparison is true only
424 /// if (A & B) == A, or all bits of A are set in B.
425 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
426 /// The part "AllZeroes" declares, that the comparison is true only
427 /// if (A & B) == 0, or all bits of A are cleared in B.
428 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
429 /// The part "Mixed" declares, that (A & B) == C and C might or might not
430 /// contain any number of one bits and zero bits.
431 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
432 /// The Part "Not" means, that in above descriptions "==" should be replaced
434 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
435 /// If the mask A contains a single bit, then the following is equivalent:
436 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
437 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
438 enum MaskedICmpType {
439 FoldMskICmp_AMask_AllOnes = 1,
440 FoldMskICmp_AMask_NotAllOnes = 2,
441 FoldMskICmp_BMask_AllOnes = 4,
442 FoldMskICmp_BMask_NotAllOnes = 8,
443 FoldMskICmp_Mask_AllZeroes = 16,
444 FoldMskICmp_Mask_NotAllZeroes = 32,
445 FoldMskICmp_AMask_Mixed = 64,
446 FoldMskICmp_AMask_NotMixed = 128,
447 FoldMskICmp_BMask_Mixed = 256,
448 FoldMskICmp_BMask_NotMixed = 512
451 /// Return the set of pattern classes (from MaskedICmpType)
452 /// that (icmp SCC (A & B), C) satisfies.
453 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
454 ICmpInst::Predicate SCC)
456 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
457 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
458 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
459 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
460 bool icmp_abit = (ACst && !ACst->isZero() &&
461 ACst->getValue().isPowerOf2());
462 bool icmp_bbit = (BCst && !BCst->isZero() &&
463 BCst->getValue().isPowerOf2());
465 if (CCst && CCst->isZero()) {
466 // if C is zero, then both A and B qualify as mask
467 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
468 FoldMskICmp_Mask_AllZeroes |
469 FoldMskICmp_AMask_Mixed |
470 FoldMskICmp_BMask_Mixed)
471 : (FoldMskICmp_Mask_NotAllZeroes |
472 FoldMskICmp_Mask_NotAllZeroes |
473 FoldMskICmp_AMask_NotMixed |
474 FoldMskICmp_BMask_NotMixed));
476 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
477 FoldMskICmp_AMask_NotMixed)
478 : (FoldMskICmp_AMask_AllOnes |
479 FoldMskICmp_AMask_Mixed));
481 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
482 FoldMskICmp_BMask_NotMixed)
483 : (FoldMskICmp_BMask_AllOnes |
484 FoldMskICmp_BMask_Mixed));
488 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
489 FoldMskICmp_AMask_Mixed)
490 : (FoldMskICmp_AMask_NotAllOnes |
491 FoldMskICmp_AMask_NotMixed));
493 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
494 FoldMskICmp_AMask_NotMixed)
495 : (FoldMskICmp_Mask_AllZeroes |
496 FoldMskICmp_AMask_Mixed));
497 } else if (ACst && CCst &&
498 ConstantExpr::getAnd(ACst, CCst) == CCst) {
499 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
500 : FoldMskICmp_AMask_NotMixed);
503 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
504 FoldMskICmp_BMask_Mixed)
505 : (FoldMskICmp_BMask_NotAllOnes |
506 FoldMskICmp_BMask_NotMixed));
508 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
509 FoldMskICmp_BMask_NotMixed)
510 : (FoldMskICmp_Mask_AllZeroes |
511 FoldMskICmp_BMask_Mixed));
512 } else if (BCst && CCst &&
513 ConstantExpr::getAnd(BCst, CCst) == CCst) {
514 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
515 : FoldMskICmp_BMask_NotMixed);
520 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
521 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
522 /// is adjacent to the corresponding normal flag (recording ==), this just
523 /// involves swapping those bits over.
524 static unsigned conjugateICmpMask(unsigned Mask) {
526 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
527 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
528 FoldMskICmp_BMask_Mixed))
532 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
533 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
534 FoldMskICmp_BMask_NotMixed))
540 /// Decompose an icmp into the form ((X & Y) pred Z) if possible.
541 /// The returned predicate is either == or !=. Returns false if
542 /// decomposition fails.
543 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
544 Value *&X, Value *&Y, Value *&Z) {
545 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
549 switch (I->getPredicate()) {
552 case ICmpInst::ICMP_SLT:
553 // X < 0 is equivalent to (X & SignBit) != 0.
556 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
557 Pred = ICmpInst::ICMP_NE;
559 case ICmpInst::ICMP_SGT:
560 // X > -1 is equivalent to (X & SignBit) == 0.
561 if (!C->isAllOnesValue())
563 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
564 Pred = ICmpInst::ICMP_EQ;
566 case ICmpInst::ICMP_ULT:
567 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
568 if (!C->getValue().isPowerOf2())
570 Y = ConstantInt::get(I->getContext(), -C->getValue());
571 Pred = ICmpInst::ICMP_EQ;
573 case ICmpInst::ICMP_UGT:
574 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
575 if (!(C->getValue() + 1).isPowerOf2())
577 Y = ConstantInt::get(I->getContext(), ~C->getValue());
578 Pred = ICmpInst::ICMP_NE;
582 X = I->getOperand(0);
583 Z = ConstantInt::getNullValue(C->getType());
587 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
588 /// Return the set of pattern classes (from MaskedICmpType)
589 /// that both LHS and RHS satisfy.
590 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
591 Value*& B, Value*& C,
592 Value*& D, Value*& E,
593 ICmpInst *LHS, ICmpInst *RHS,
594 ICmpInst::Predicate &LHSCC,
595 ICmpInst::Predicate &RHSCC) {
596 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
597 // vectors are not (yet?) supported
598 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
600 // Here comes the tricky part:
601 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
602 // and L11 & L12 == L21 & L22. The same goes for RHS.
603 // Now we must find those components L** and R**, that are equal, so
604 // that we can extract the parameters A, B, C, D, and E for the canonical
606 Value *L1 = LHS->getOperand(0);
607 Value *L2 = LHS->getOperand(1);
608 Value *L11,*L12,*L21,*L22;
609 // Check whether the icmp can be decomposed into a bit test.
610 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
611 L21 = L22 = L1 = nullptr;
613 // Look for ANDs in the LHS icmp.
614 if (!L1->getType()->isIntegerTy()) {
615 // You can icmp pointers, for example. They really aren't masks.
617 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
618 // Any icmp can be viewed as being trivially masked; if it allows us to
619 // remove one, it's worth it.
621 L12 = Constant::getAllOnesValue(L1->getType());
624 if (!L2->getType()->isIntegerTy()) {
625 // You can icmp pointers, for example. They really aren't masks.
627 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
629 L22 = Constant::getAllOnesValue(L2->getType());
633 // Bail if LHS was a icmp that can't be decomposed into an equality.
634 if (!ICmpInst::isEquality(LHSCC))
637 Value *R1 = RHS->getOperand(0);
638 Value *R2 = RHS->getOperand(1);
641 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
642 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
644 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
649 E = R2; R1 = nullptr; ok = true;
650 } else if (R1->getType()->isIntegerTy()) {
651 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
652 // As before, model no mask as a trivial mask if it'll let us do an
655 R12 = Constant::getAllOnesValue(R1->getType());
658 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
659 A = R11; D = R12; E = R2; ok = true;
660 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
661 A = R12; D = R11; E = R2; ok = true;
665 // Bail if RHS was a icmp that can't be decomposed into an equality.
666 if (!ICmpInst::isEquality(RHSCC))
669 // Look for ANDs in on the right side of the RHS icmp.
670 if (!ok && R2->getType()->isIntegerTy()) {
671 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
673 R12 = Constant::getAllOnesValue(R2->getType());
676 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
677 A = R11; D = R12; E = R1; ok = true;
678 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
679 A = R12; D = R11; E = R1; ok = true;
689 } else if (L12 == A) {
691 } else if (L21 == A) {
693 } else if (L22 == A) {
697 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
698 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
699 return left_type & right_type;
702 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
703 /// into a single (icmp(A & X) ==/!= Y).
704 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
705 llvm::InstCombiner::BuilderTy *Builder) {
706 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
707 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
708 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
710 if (mask == 0) return nullptr;
711 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
712 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
714 // In full generality:
715 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
716 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
718 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
719 // equivalent to (icmp (A & X) !Op Y).
721 // Therefore, we can pretend for the rest of this function that we're dealing
722 // with the conjunction, provided we flip the sense of any comparisons (both
723 // input and output).
725 // In most cases we're going to produce an EQ for the "&&" case.
726 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
728 // Convert the masking analysis into its equivalent with negated
730 mask = conjugateICmpMask(mask);
733 if (mask & FoldMskICmp_Mask_AllZeroes) {
734 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
735 // -> (icmp eq (A & (B|D)), 0)
736 Value *newOr = Builder->CreateOr(B, D);
737 Value *newAnd = Builder->CreateAnd(A, newOr);
738 // we can't use C as zero, because we might actually handle
739 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
740 // with B and D, having a single bit set
741 Value *zero = Constant::getNullValue(A->getType());
742 return Builder->CreateICmp(NEWCC, newAnd, zero);
744 if (mask & FoldMskICmp_BMask_AllOnes) {
745 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
746 // -> (icmp eq (A & (B|D)), (B|D))
747 Value *newOr = Builder->CreateOr(B, D);
748 Value *newAnd = Builder->CreateAnd(A, newOr);
749 return Builder->CreateICmp(NEWCC, newAnd, newOr);
751 if (mask & FoldMskICmp_AMask_AllOnes) {
752 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
753 // -> (icmp eq (A & (B&D)), A)
754 Value *newAnd1 = Builder->CreateAnd(B, D);
755 Value *newAnd = Builder->CreateAnd(A, newAnd1);
756 return Builder->CreateICmp(NEWCC, newAnd, A);
759 // Remaining cases assume at least that B and D are constant, and depend on
760 // their actual values. This isn't strictly, necessary, just a "handle the
761 // easy cases for now" decision.
762 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
763 if (!BCst) return nullptr;
764 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
765 if (!DCst) return nullptr;
767 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
768 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
769 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
770 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
771 // Only valid if one of the masks is a superset of the other (check "B&D" is
772 // the same as either B or D).
773 APInt NewMask = BCst->getValue() & DCst->getValue();
775 if (NewMask == BCst->getValue())
777 else if (NewMask == DCst->getValue())
780 if (mask & FoldMskICmp_AMask_NotAllOnes) {
781 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
782 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
783 // Only valid if one of the masks is a superset of the other (check "B|D" is
784 // the same as either B or D).
785 APInt NewMask = BCst->getValue() | DCst->getValue();
787 if (NewMask == BCst->getValue())
789 else if (NewMask == DCst->getValue())
792 if (mask & FoldMskICmp_BMask_Mixed) {
793 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
794 // We already know that B & C == C && D & E == E.
795 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
796 // C and E, which are shared by both the mask B and the mask D, don't
797 // contradict, then we can transform to
798 // -> (icmp eq (A & (B|D)), (C|E))
799 // Currently, we only handle the case of B, C, D, and E being constant.
800 // we can't simply use C and E, because we might actually handle
801 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
802 // with B and D, having a single bit set
803 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
804 if (!CCst) return nullptr;
805 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
806 if (!ECst) return nullptr;
808 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
810 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
811 // if there is a conflict we should actually return a false for the
813 if (((BCst->getValue() & DCst->getValue()) &
814 (CCst->getValue() ^ ECst->getValue())) != 0)
815 return ConstantInt::get(LHS->getType(), !IsAnd);
816 Value *newOr1 = Builder->CreateOr(B, D);
817 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
818 Value *newAnd = Builder->CreateAnd(A, newOr1);
819 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
824 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
825 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
826 /// If \p Inverted is true then the check is for the inverted range, e.g.
827 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
828 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
830 // Check the lower range comparison, e.g. x >= 0
831 // InstCombine already ensured that if there is a constant it's on the RHS.
832 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
836 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
837 Cmp0->getPredicate());
839 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
840 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
841 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
844 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
845 Cmp1->getPredicate());
847 Value *Input = Cmp0->getOperand(0);
849 if (Cmp1->getOperand(0) == Input) {
850 // For the upper range compare we have: icmp x, n
851 RangeEnd = Cmp1->getOperand(1);
852 } else if (Cmp1->getOperand(1) == Input) {
853 // For the upper range compare we have: icmp n, x
854 RangeEnd = Cmp1->getOperand(0);
855 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
860 // Check the upper range comparison, e.g. x < n
861 ICmpInst::Predicate NewPred;
863 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
864 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
865 default: return nullptr;
868 // This simplification is only valid if the upper range is not negative.
869 bool IsNegative, IsNotNegative;
870 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
875 NewPred = ICmpInst::getInversePredicate(NewPred);
877 return Builder->CreateICmp(NewPred, Input, RangeEnd);
880 /// Fold (icmp)&(icmp) if possible.
881 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
882 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
884 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
885 if (PredicatesFoldable(LHSCC, RHSCC)) {
886 if (LHS->getOperand(0) == RHS->getOperand(1) &&
887 LHS->getOperand(1) == RHS->getOperand(0))
889 if (LHS->getOperand(0) == RHS->getOperand(0) &&
890 LHS->getOperand(1) == RHS->getOperand(1)) {
891 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
892 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
893 bool isSigned = LHS->isSigned() || RHS->isSigned();
894 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
898 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
899 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
902 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
903 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
906 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
907 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
910 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
911 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
912 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
913 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
914 if (!LHSCst || !RHSCst) return nullptr;
916 if (LHSCst == RHSCst && LHSCC == RHSCC) {
917 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
918 // where C is a power of 2
919 if (LHSCC == ICmpInst::ICMP_ULT &&
920 LHSCst->getValue().isPowerOf2()) {
921 Value *NewOr = Builder->CreateOr(Val, Val2);
922 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
925 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
926 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
927 Value *NewOr = Builder->CreateOr(Val, Val2);
928 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
932 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
933 // where CMAX is the all ones value for the truncated type,
934 // iff the lower bits of C2 and CA are zero.
935 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
936 LHS->hasOneUse() && RHS->hasOneUse()) {
938 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
940 // (trunc x) == C1 & (and x, CA) == C2
941 // (and x, CA) == C2 & (trunc x) == C1
942 if (match(Val2, m_Trunc(m_Value(V))) &&
943 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
946 } else if (match(Val, m_Trunc(m_Value(V))) &&
947 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
952 if (SmallCst && BigCst) {
953 unsigned BigBitSize = BigCst->getType()->getBitWidth();
954 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
956 // Check that the low bits are zero.
957 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
958 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
959 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
960 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
961 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
962 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
967 // From here on, we only handle:
968 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
969 if (Val != Val2) return nullptr;
971 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
972 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
973 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
974 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
975 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
978 // Make a constant range that's the intersection of the two icmp ranges.
979 // If the intersection is empty, we know that the result is false.
980 ConstantRange LHSRange =
981 ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
982 ConstantRange RHSRange =
983 ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
985 if (LHSRange.intersectWith(RHSRange).isEmptySet())
986 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
988 // We can't fold (ugt x, C) & (sgt x, C2).
989 if (!PredicatesFoldable(LHSCC, RHSCC))
992 // Ensure that the larger constant is on the RHS.
994 if (CmpInst::isSigned(LHSCC) ||
995 (ICmpInst::isEquality(LHSCC) &&
996 CmpInst::isSigned(RHSCC)))
997 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
999 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1002 std::swap(LHS, RHS);
1003 std::swap(LHSCst, RHSCst);
1004 std::swap(LHSCC, RHSCC);
1007 // At this point, we know we have two icmp instructions
1008 // comparing a value against two constants and and'ing the result
1009 // together. Because of the above check, we know that we only have
1010 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1011 // (from the icmp folding check above), that the two constants
1012 // are not equal and that the larger constant is on the RHS
1013 assert(LHSCst != RHSCst && "Compares not folded above?");
1016 default: llvm_unreachable("Unknown integer condition code!");
1017 case ICmpInst::ICMP_EQ:
1019 default: llvm_unreachable("Unknown integer condition code!");
1020 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1021 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1022 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
1025 case ICmpInst::ICMP_NE:
1027 default: llvm_unreachable("Unknown integer condition code!");
1028 case ICmpInst::ICMP_ULT:
1029 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
1030 return Builder->CreateICmpULT(Val, LHSCst);
1031 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1032 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1033 break; // (X != 13 & X u< 15) -> no change
1034 case ICmpInst::ICMP_SLT:
1035 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
1036 return Builder->CreateICmpSLT(Val, LHSCst);
1037 break; // (X != 13 & X s< 15) -> no change
1038 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1039 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1040 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
1042 case ICmpInst::ICMP_NE:
1043 // Special case to get the ordering right when the values wrap around
1045 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
1046 std::swap(LHSCst, RHSCst);
1047 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1048 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1049 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1050 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1051 Val->getName()+".cmp");
1053 break; // (X != 13 & X != 15) -> no change
1056 case ICmpInst::ICMP_ULT:
1058 default: llvm_unreachable("Unknown integer condition code!");
1059 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1060 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
1061 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1062 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1064 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1065 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
1067 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1071 case ICmpInst::ICMP_SLT:
1073 default: llvm_unreachable("Unknown integer condition code!");
1074 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1076 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1077 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
1079 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1083 case ICmpInst::ICMP_UGT:
1085 default: llvm_unreachable("Unknown integer condition code!");
1086 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1087 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1089 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1091 case ICmpInst::ICMP_NE:
1092 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
1093 return Builder->CreateICmp(LHSCC, Val, RHSCst);
1094 break; // (X u> 13 & X != 15) -> no change
1095 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
1096 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1097 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1101 case ICmpInst::ICMP_SGT:
1103 default: llvm_unreachable("Unknown integer condition code!");
1104 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1105 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1107 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1109 case ICmpInst::ICMP_NE:
1110 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1111 return Builder->CreateICmp(LHSCC, Val, RHSCst);
1112 break; // (X s> 13 & X != 15) -> no change
1113 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
1114 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1115 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1124 /// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1125 /// a Value which should already be inserted into the function.
1126 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1127 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1128 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1129 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1132 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1133 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1134 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1135 // If either of the constants are nans, then the whole thing returns
1137 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1138 return Builder->getFalse();
1139 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1142 // Handle vector zeros. This occurs because the canonical form of
1143 // "fcmp ord x,x" is "fcmp ord x, 0".
1144 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1145 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1146 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1150 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1151 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1152 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1155 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1156 // Swap RHS operands to match LHS.
1157 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1158 std::swap(Op1LHS, Op1RHS);
1161 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1162 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1164 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1165 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1166 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1167 if (Op0CC == FCmpInst::FCMP_TRUE)
1169 if (Op1CC == FCmpInst::FCMP_TRUE)
1174 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1175 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1176 // uno && ord -> false
1177 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1178 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1180 std::swap(LHS, RHS);
1181 std::swap(Op0Pred, Op1Pred);
1182 std::swap(Op0Ordered, Op1Ordered);
1185 // uno && ueq -> uno && (uno || eq) -> uno
1186 // ord && olt -> ord && (ord && lt) -> olt
1187 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1189 if (Op0Ordered && (Op0Ordered == Op1Ordered))
1192 // uno && oeq -> uno && (ord && eq) -> false
1194 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1195 // ord && ueq -> ord && (uno || eq) -> oeq
1196 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1203 /// Match De Morgan's Laws:
1204 /// (~A & ~B) == (~(A | B))
1205 /// (~A | ~B) == (~(A & B))
1206 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1207 InstCombiner::BuilderTy *Builder) {
1208 auto Opcode = I.getOpcode();
1209 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1210 "Trying to match De Morgan's Laws with something other than and/or");
1212 Value *Op0 = I.getOperand(0);
1213 Value *Op1 = I.getOperand(1);
1214 // TODO: Use pattern matchers instead of dyn_cast.
1215 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1216 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1217 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1218 // Flip the logic operation.
1219 if (Opcode == Instruction::And)
1220 Opcode = Instruction::Or;
1222 Opcode = Instruction::And;
1223 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1224 I.getName() + ".demorgan");
1225 return BinaryOperator::CreateNot(LogicOp);
1231 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1232 bool Changed = SimplifyAssociativeOrCommutative(I);
1233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1235 if (Value *V = SimplifyVectorOp(I))
1236 return ReplaceInstUsesWith(I, V);
1238 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
1239 return ReplaceInstUsesWith(I, V);
1241 // (A|B)&(A|C) -> A|(B&C) etc
1242 if (Value *V = SimplifyUsingDistributiveLaws(I))
1243 return ReplaceInstUsesWith(I, V);
1245 // See if we can simplify any instructions used by the instruction whose sole
1246 // purpose is to compute bits we don't care about.
1247 if (SimplifyDemandedInstructionBits(I))
1250 if (Value *V = SimplifyBSwap(I))
1251 return ReplaceInstUsesWith(I, V);
1253 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1254 const APInt &AndRHSMask = AndRHS->getValue();
1256 // Optimize a variety of ((val OP C1) & C2) combinations...
1257 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1258 Value *Op0LHS = Op0I->getOperand(0);
1259 Value *Op0RHS = Op0I->getOperand(1);
1260 switch (Op0I->getOpcode()) {
1262 case Instruction::Xor:
1263 case Instruction::Or: {
1264 // If the mask is only needed on one incoming arm, push it up.
1265 if (!Op0I->hasOneUse()) break;
1267 APInt NotAndRHS(~AndRHSMask);
1268 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1269 // Not masking anything out for the LHS, move to RHS.
1270 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1271 Op0RHS->getName()+".masked");
1272 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1274 if (!isa<Constant>(Op0RHS) &&
1275 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1276 // Not masking anything out for the RHS, move to LHS.
1277 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1278 Op0LHS->getName()+".masked");
1279 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1284 case Instruction::Add:
1285 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1286 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1287 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1288 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1289 return BinaryOperator::CreateAnd(V, AndRHS);
1290 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1291 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1294 case Instruction::Sub:
1295 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1296 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1297 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1298 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1299 return BinaryOperator::CreateAnd(V, AndRHS);
1302 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1303 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1305 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1306 // has 1's for all bits that the subtraction with A might affect.
1307 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1308 uint32_t BitWidth = AndRHSMask.getBitWidth();
1309 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1310 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1312 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
1313 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1314 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1319 case Instruction::Shl:
1320 case Instruction::LShr:
1321 // (1 << x) & 1 --> zext(x == 0)
1322 // (1 >> x) & 1 --> zext(x == 0)
1323 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1325 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1326 return new ZExtInst(NewICmp, I.getType());
1331 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1332 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1336 // If this is an integer truncation, and if the source is an 'and' with
1337 // immediate, transform it. This frequently occurs for bitfield accesses.
1339 Value *X = nullptr; ConstantInt *YC = nullptr;
1340 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1341 // Change: and (trunc (and X, YC) to T), C2
1342 // into : and (trunc X to T), trunc(YC) & C2
1343 // This will fold the two constants together, which may allow
1344 // other simplifications.
1345 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1346 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1347 C3 = ConstantExpr::getAnd(C3, AndRHS);
1348 return BinaryOperator::CreateAnd(NewCast, C3);
1352 // Try to fold constant and into select arguments.
1353 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1354 if (Instruction *R = FoldOpIntoSelect(I, SI))
1356 if (isa<PHINode>(Op0))
1357 if (Instruction *NV = FoldOpIntoPhi(I))
1361 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1365 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1366 // (A|B) & ~(A&B) -> A^B
1367 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1368 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1369 ((A == C && B == D) || (A == D && B == C)))
1370 return BinaryOperator::CreateXor(A, B);
1372 // ~(A&B) & (A|B) -> A^B
1373 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1374 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1375 ((A == C && B == D) || (A == D && B == C)))
1376 return BinaryOperator::CreateXor(A, B);
1378 // A&(A^B) => A & ~B
1380 Value *tmpOp0 = Op0;
1381 Value *tmpOp1 = Op1;
1382 if (Op0->hasOneUse() &&
1383 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1384 if (A == Op1 || B == Op1 ) {
1391 if (tmpOp1->hasOneUse() &&
1392 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1396 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1397 // A is originally -1 (or a vector of -1 and undefs), then we enter
1398 // an endless loop. By checking that A is non-constant we ensure that
1399 // we will never get to the loop.
1400 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1401 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1405 // (A&((~A)|B)) -> A&B
1406 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1407 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1408 return BinaryOperator::CreateAnd(A, Op1);
1409 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1410 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1411 return BinaryOperator::CreateAnd(A, Op0);
1413 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1414 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1415 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1416 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1417 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1419 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1420 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1421 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1422 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1423 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1425 // (A | B) & ((~A) ^ B) -> (A & B)
1426 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1427 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1428 return BinaryOperator::CreateAnd(A, B);
1430 // ((~A) ^ B) & (A | B) -> (A & B)
1431 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1432 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1433 return BinaryOperator::CreateAnd(A, B);
1437 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1438 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1440 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1441 return ReplaceInstUsesWith(I, Res);
1443 // TODO: Make this recursive; it's a little tricky because an arbitrary
1444 // number of 'and' instructions might have to be created.
1446 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1447 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1448 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1449 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1450 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1451 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1452 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1454 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1455 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1456 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1457 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1458 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1459 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1460 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1464 // If and'ing two fcmp, try combine them into one.
1465 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1466 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1467 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1468 return ReplaceInstUsesWith(I, Res);
1471 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1472 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1473 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1474 Type *SrcTy = Op0C->getOperand(0)->getType();
1475 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1476 SrcTy == Op1C->getOperand(0)->getType() &&
1477 SrcTy->isIntOrIntVectorTy()) {
1478 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1480 // Only do this if the casts both really cause code to be generated.
1481 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1482 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1483 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1484 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1487 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1488 // cast is otherwise not optimizable. This happens for vector sexts.
1489 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1490 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1491 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1492 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1494 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1495 // cast is otherwise not optimizable. This happens for vector sexts.
1496 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1497 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1498 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1499 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1505 bool OpsSwapped = false;
1506 // Canonicalize SExt or Not to the LHS
1507 if (match(Op1, m_SExt(m_Value())) ||
1508 match(Op1, m_Not(m_Value()))) {
1509 std::swap(Op0, Op1);
1513 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1514 if (match(Op0, m_SExt(m_Value(X))) &&
1515 X->getType()->getScalarType()->isIntegerTy(1)) {
1516 Value *Zero = Constant::getNullValue(Op1->getType());
1517 return SelectInst::Create(X, Op1, Zero);
1520 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1521 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1522 X->getType()->getScalarType()->isIntegerTy(1)) {
1523 Value *Zero = Constant::getNullValue(Op0->getType());
1524 return SelectInst::Create(X, Zero, Op1);
1528 std::swap(Op0, Op1);
1531 return Changed ? &I : nullptr;
1534 /// Analyze the specified subexpression and see if it is capable of providing
1535 /// pieces of a bswap. The subexpression provides pieces of a bswap if it is
1536 /// proven that each of the non-zero bytes in the output of the expression came
1537 /// from the corresponding "byte swapped" byte in some other value.
1538 /// For example, if the current subexpression is "(shl i32 %X, 24)" then
1539 /// we know that the expression deposits the low byte of %X into the high byte
1540 /// of the bswap result and that all other bytes are zero. This expression is
1541 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1544 /// This function returns true if the match was unsuccessful and false if so.
1545 /// On entry to the function the "OverallLeftShift" is a signed integer value
1546 /// indicating the number of bytes that the subexpression is later shifted. For
1547 /// example, if the expression is later right shifted by 16 bits, the
1548 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1549 /// byte of ByteValues is actually being set.
1551 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1552 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1553 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1554 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1555 /// always in the local (OverallLeftShift) coordinate space.
1557 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1558 SmallVectorImpl<Value *> &ByteValues) {
1559 if (Instruction *I = dyn_cast<Instruction>(V)) {
1560 // If this is an or instruction, it may be an inner node of the bswap.
1561 if (I->getOpcode() == Instruction::Or) {
1562 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1564 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1568 // If this is a logical shift by a constant multiple of 8, recurse with
1569 // OverallLeftShift and ByteMask adjusted.
1570 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1572 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1573 // Ensure the shift amount is defined and of a byte value.
1574 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1577 unsigned ByteShift = ShAmt >> 3;
1578 if (I->getOpcode() == Instruction::Shl) {
1579 // X << 2 -> collect(X, +2)
1580 OverallLeftShift += ByteShift;
1581 ByteMask >>= ByteShift;
1583 // X >>u 2 -> collect(X, -2)
1584 OverallLeftShift -= ByteShift;
1585 ByteMask <<= ByteShift;
1586 ByteMask &= (~0U >> (32-ByteValues.size()));
1589 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1590 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1592 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1596 // If this is a logical 'and' with a mask that clears bytes, clear the
1597 // corresponding bytes in ByteMask.
1598 if (I->getOpcode() == Instruction::And &&
1599 isa<ConstantInt>(I->getOperand(1))) {
1600 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1601 unsigned NumBytes = ByteValues.size();
1602 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1603 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1605 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1606 // If this byte is masked out by a later operation, we don't care what
1608 if ((ByteMask & (1 << i)) == 0)
1611 // If the AndMask is all zeros for this byte, clear the bit.
1612 APInt MaskB = AndMask & Byte;
1614 ByteMask &= ~(1U << i);
1618 // If the AndMask is not all ones for this byte, it's not a bytezap.
1622 // Otherwise, this byte is kept.
1625 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1630 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1631 // the input value to the bswap. Some observations: 1) if more than one byte
1632 // is demanded from this input, then it could not be successfully assembled
1633 // into a byteswap. At least one of the two bytes would not be aligned with
1634 // their ultimate destination.
1635 if (!isPowerOf2_32(ByteMask)) return true;
1636 unsigned InputByteNo = countTrailingZeros(ByteMask);
1638 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1639 // is demanded, it needs to go into byte 0 of the result. This means that the
1640 // byte needs to be shifted until it lands in the right byte bucket. The
1641 // shift amount depends on the position: if the byte is coming from the high
1642 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1643 // low part, it must be shifted left.
1644 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1645 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1648 // If the destination byte value is already defined, the values are or'd
1649 // together, which isn't a bswap (unless it's an or of the same bits).
1650 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1652 ByteValues[DestByteNo] = V;
1656 /// Given an OR instruction, check to see if this is a bswap idiom.
1657 /// If so, insert the new bswap intrinsic and return it.
1658 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1659 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1660 if (!ITy || ITy->getBitWidth() % 16 ||
1661 // ByteMask only allows up to 32-byte values.
1662 ITy->getBitWidth() > 32*8)
1663 return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
1665 /// ByteValues - For each byte of the result, we keep track of which value
1666 /// defines each byte.
1667 SmallVector<Value*, 8> ByteValues;
1668 ByteValues.resize(ITy->getBitWidth()/8);
1670 // Try to find all the pieces corresponding to the bswap.
1671 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1672 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1675 // Check to see if all of the bytes come from the same value.
1676 Value *V = ByteValues[0];
1677 if (!V) return nullptr; // Didn't find a byte? Must be zero.
1679 // Check to make sure that all of the bytes come from the same value.
1680 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1681 if (ByteValues[i] != V)
1683 Module *M = I.getParent()->getParent()->getParent();
1684 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1685 return CallInst::Create(F, V);
1688 /// We have an expression of the form (A&C)|(B&D). Check if A is (cond?-1:0)
1689 /// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1690 /// expression to "cond ? C : D or B".
1691 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1692 Value *C, Value *D) {
1693 // If A is not a select of -1/0, this cannot match.
1694 Value *Cond = nullptr;
1695 if (!match(A, m_SExt(m_Value(Cond))) ||
1696 !Cond->getType()->isIntegerTy(1))
1699 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1700 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1701 return SelectInst::Create(Cond, C, B);
1702 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1703 return SelectInst::Create(Cond, C, B);
1705 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1706 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1707 return SelectInst::Create(Cond, C, D);
1708 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1709 return SelectInst::Create(Cond, C, D);
1713 /// Fold (icmp)|(icmp) if possible.
1714 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1715 Instruction *CxtI) {
1716 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1718 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1719 // if K1 and K2 are a one-bit mask.
1720 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1721 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1723 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1724 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1726 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1727 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1728 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1729 LAnd->getOpcode() == Instruction::And &&
1730 RAnd->getOpcode() == Instruction::And) {
1732 Value *Mask = nullptr;
1733 Value *Masked = nullptr;
1734 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1735 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1737 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1739 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1740 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1741 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1742 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1744 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1746 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1747 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1751 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1755 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1756 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1757 // The original condition actually refers to the following two ranges:
1758 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1759 // We can fold these two ranges if:
1760 // 1) C1 and C2 is unsigned greater than C3.
1761 // 2) The two ranges are separated.
1762 // 3) C1 ^ C2 is one-bit mask.
1763 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1764 // This implies all values in the two ranges differ by exactly one bit.
1766 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1767 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1768 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1769 LHSCst->getValue() == (RHSCst->getValue())) {
1771 Value *LAdd = LHS->getOperand(0);
1772 Value *RAdd = RHS->getOperand(0);
1774 Value *LAddOpnd, *RAddOpnd;
1775 ConstantInt *LAddCst, *RAddCst;
1776 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1777 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1778 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1779 RAddCst->getValue().ugt(LHSCst->getValue())) {
1781 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1782 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1783 ConstantInt *MaxAddCst = nullptr;
1784 if (LAddCst->getValue().ult(RAddCst->getValue()))
1785 MaxAddCst = RAddCst;
1787 MaxAddCst = LAddCst;
1789 APInt RRangeLow = -RAddCst->getValue();
1790 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1791 APInt LRangeLow = -LAddCst->getValue();
1792 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1793 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1794 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1795 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1796 : RRangeLow - LRangeLow;
1798 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1799 RangeDiff.ugt(LHSCst->getValue())) {
1800 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1802 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1803 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1804 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1810 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1811 if (PredicatesFoldable(LHSCC, RHSCC)) {
1812 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1813 LHS->getOperand(1) == RHS->getOperand(0))
1814 LHS->swapOperands();
1815 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1816 LHS->getOperand(1) == RHS->getOperand(1)) {
1817 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1818 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1819 bool isSigned = LHS->isSigned() || RHS->isSigned();
1820 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1824 // handle (roughly):
1825 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1826 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1829 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1830 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1831 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1832 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1833 Value *A = nullptr, *B = nullptr;
1834 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1836 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1838 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1839 A = RHS->getOperand(1);
1841 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1842 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1843 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1845 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1847 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1848 A = LHS->getOperand(1);
1851 return Builder->CreateICmp(
1853 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1856 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1857 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1860 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1861 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1864 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1865 if (!LHSCst || !RHSCst) return nullptr;
1867 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1868 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1869 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1870 Value *NewOr = Builder->CreateOr(Val, Val2);
1871 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1875 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1876 // iff C2 + CA == C1.
1877 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1878 ConstantInt *AddCst;
1879 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1880 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1881 return Builder->CreateICmpULE(Val, LHSCst);
1884 // From here on, we only handle:
1885 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1886 if (Val != Val2) return nullptr;
1888 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1889 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1890 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1891 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1892 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1895 // We can't fold (ugt x, C) | (sgt x, C2).
1896 if (!PredicatesFoldable(LHSCC, RHSCC))
1899 // Ensure that the larger constant is on the RHS.
1901 if (CmpInst::isSigned(LHSCC) ||
1902 (ICmpInst::isEquality(LHSCC) &&
1903 CmpInst::isSigned(RHSCC)))
1904 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1906 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1909 std::swap(LHS, RHS);
1910 std::swap(LHSCst, RHSCst);
1911 std::swap(LHSCC, RHSCC);
1914 // At this point, we know we have two icmp instructions
1915 // comparing a value against two constants and or'ing the result
1916 // together. Because of the above check, we know that we only have
1917 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1918 // icmp folding check above), that the two constants are not
1920 assert(LHSCst != RHSCst && "Compares not folded above?");
1923 default: llvm_unreachable("Unknown integer condition code!");
1924 case ICmpInst::ICMP_EQ:
1926 default: llvm_unreachable("Unknown integer condition code!");
1927 case ICmpInst::ICMP_EQ:
1928 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1929 // if LHSCst and RHSCst differ only by one bit:
1930 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1931 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1933 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1934 if (Xor.isPowerOf2()) {
1935 Value *NegCst = Builder->getInt(~Xor);
1936 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1937 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1941 if (LHSCst == SubOne(RHSCst)) {
1942 // (X == 13 | X == 14) -> X-13 <u 2
1943 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1944 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1945 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1946 return Builder->CreateICmpULT(Add, AddCST);
1949 break; // (X == 13 | X == 15) -> no change
1950 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1951 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1953 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1954 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1955 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1959 case ICmpInst::ICMP_NE:
1961 default: llvm_unreachable("Unknown integer condition code!");
1962 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1963 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1964 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1966 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1967 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1968 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1969 return Builder->getTrue();
1971 case ICmpInst::ICMP_ULT:
1973 default: llvm_unreachable("Unknown integer condition code!");
1974 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1976 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1977 // If RHSCst is [us]MAXINT, it is always false. Not handling
1978 // this can cause overflow.
1979 if (RHSCst->isMaxValue(false))
1981 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1982 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1984 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1985 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1987 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1991 case ICmpInst::ICMP_SLT:
1993 default: llvm_unreachable("Unknown integer condition code!");
1994 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1996 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1997 // If RHSCst is [us]MAXINT, it is always false. Not handling
1998 // this can cause overflow.
1999 if (RHSCst->isMaxValue(true))
2001 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
2002 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2004 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2005 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
2007 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2011 case ICmpInst::ICMP_UGT:
2013 default: llvm_unreachable("Unknown integer condition code!");
2014 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2015 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
2017 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2019 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2020 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
2021 return Builder->getTrue();
2022 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2026 case ICmpInst::ICMP_SGT:
2028 default: llvm_unreachable("Unknown integer condition code!");
2029 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2030 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
2032 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2034 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2035 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
2036 return Builder->getTrue();
2037 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2045 /// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
2046 /// a Value which should already be inserted into the function.
2047 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
2048 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2049 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2050 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2051 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2052 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2053 // If either of the constants are nans, then the whole thing returns
2055 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
2056 return Builder->getTrue();
2058 // Otherwise, no need to compare the two constants, compare the
2060 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2063 // Handle vector zeros. This occurs because the canonical form of
2064 // "fcmp uno x,x" is "fcmp uno x, 0".
2065 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2066 isa<ConstantAggregateZero>(RHS->getOperand(1)))
2067 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2072 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2073 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2074 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2076 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2077 // Swap RHS operands to match LHS.
2078 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2079 std::swap(Op1LHS, Op1RHS);
2081 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2082 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2084 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
2085 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
2086 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
2087 if (Op0CC == FCmpInst::FCMP_FALSE)
2089 if (Op1CC == FCmpInst::FCMP_FALSE)
2093 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2094 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2095 if (Op0Ordered == Op1Ordered) {
2096 // If both are ordered or unordered, return a new fcmp with
2097 // or'ed predicates.
2098 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
2104 /// This helper function folds:
2106 /// ((A | B) & C1) | (B & C2)
2112 /// when the XOR of the two constants is "all ones" (-1).
2113 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2114 Value *A, Value *B, Value *C) {
2115 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2116 if (!CI1) return nullptr;
2118 Value *V1 = nullptr;
2119 ConstantInt *CI2 = nullptr;
2120 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
2122 APInt Xor = CI1->getValue() ^ CI2->getValue();
2123 if (!Xor.isAllOnesValue()) return nullptr;
2125 if (V1 == A || V1 == B) {
2126 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2127 return BinaryOperator::CreateOr(NewOp, V1);
2133 /// \brief This helper function folds:
2135 /// ((A | B) & C1) ^ (B & C2)
2141 /// when the XOR of the two constants is "all ones" (-1).
2142 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2143 Value *A, Value *B, Value *C) {
2144 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2148 Value *V1 = nullptr;
2149 ConstantInt *CI2 = nullptr;
2150 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2153 APInt Xor = CI1->getValue() ^ CI2->getValue();
2154 if (!Xor.isAllOnesValue())
2157 if (V1 == A || V1 == B) {
2158 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2159 return BinaryOperator::CreateXor(NewOp, V1);
2165 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2166 bool Changed = SimplifyAssociativeOrCommutative(I);
2167 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2169 if (Value *V = SimplifyVectorOp(I))
2170 return ReplaceInstUsesWith(I, V);
2172 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
2173 return ReplaceInstUsesWith(I, V);
2175 // (A&B)|(A&C) -> A&(B|C) etc
2176 if (Value *V = SimplifyUsingDistributiveLaws(I))
2177 return ReplaceInstUsesWith(I, V);
2179 // See if we can simplify any instructions used by the instruction whose sole
2180 // purpose is to compute bits we don't care about.
2181 if (SimplifyDemandedInstructionBits(I))
2184 if (Value *V = SimplifyBSwap(I))
2185 return ReplaceInstUsesWith(I, V);
2187 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2188 ConstantInt *C1 = nullptr; Value *X = nullptr;
2189 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2190 // iff (C1 & C2) == 0.
2191 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
2192 (RHS->getValue() & C1->getValue()) != 0 &&
2194 Value *Or = Builder->CreateOr(X, RHS);
2196 return BinaryOperator::CreateAnd(Or,
2197 Builder->getInt(RHS->getValue() | C1->getValue()));
2200 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2201 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2203 Value *Or = Builder->CreateOr(X, RHS);
2205 return BinaryOperator::CreateXor(Or,
2206 Builder->getInt(C1->getValue() & ~RHS->getValue()));
2209 // Try to fold constant and into select arguments.
2210 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2211 if (Instruction *R = FoldOpIntoSelect(I, SI))
2214 if (isa<PHINode>(Op0))
2215 if (Instruction *NV = FoldOpIntoPhi(I))
2219 Value *A = nullptr, *B = nullptr;
2220 ConstantInt *C1 = nullptr, *C2 = nullptr;
2222 // (A | B) | C and A | (B | C) -> bswap if possible.
2223 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
2224 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2225 match(Op1, m_Or(m_Value(), m_Value())) ||
2226 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2227 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
2228 if (Instruction *BSwap = MatchBSwap(I))
2232 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2233 if (Op0->hasOneUse() &&
2234 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2235 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
2236 Value *NOr = Builder->CreateOr(A, Op1);
2238 return BinaryOperator::CreateXor(NOr, C1);
2241 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2242 if (Op1->hasOneUse() &&
2243 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2244 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
2245 Value *NOr = Builder->CreateOr(A, Op0);
2247 return BinaryOperator::CreateXor(NOr, C1);
2250 // ((~A & B) | A) -> (A | B)
2251 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2252 match(Op1, m_Specific(A)))
2253 return BinaryOperator::CreateOr(A, B);
2255 // ((A & B) | ~A) -> (~A | B)
2256 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2257 match(Op1, m_Not(m_Specific(A))))
2258 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2260 // (A & (~B)) | (A ^ B) -> (A ^ B)
2261 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2262 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2263 return BinaryOperator::CreateXor(A, B);
2265 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2266 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2267 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2268 return BinaryOperator::CreateXor(A, B);
2271 Value *C = nullptr, *D = nullptr;
2272 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2273 match(Op1, m_And(m_Value(B), m_Value(D)))) {
2274 Value *V1 = nullptr, *V2 = nullptr;
2275 C1 = dyn_cast<ConstantInt>(C);
2276 C2 = dyn_cast<ConstantInt>(D);
2277 if (C1 && C2) { // (A & C1)|(B & C2)
2278 if ((C1->getValue() & C2->getValue()) == 0) {
2279 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2280 // iff (C1&C2) == 0 and (N&~C1) == 0
2281 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2283 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2285 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
2286 return BinaryOperator::CreateAnd(A,
2287 Builder->getInt(C1->getValue()|C2->getValue()));
2288 // Or commutes, try both ways.
2289 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2291 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2293 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
2294 return BinaryOperator::CreateAnd(B,
2295 Builder->getInt(C1->getValue()|C2->getValue()));
2297 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2298 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2299 ConstantInt *C3 = nullptr, *C4 = nullptr;
2300 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2301 (C3->getValue() & ~C1->getValue()) == 0 &&
2302 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2303 (C4->getValue() & ~C2->getValue()) == 0) {
2304 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2305 return BinaryOperator::CreateAnd(V2,
2306 Builder->getInt(C1->getValue()|C2->getValue()));
2311 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2312 // Don't do this for vector select idioms, the code generator doesn't handle
2314 if (!I.getType()->isVectorTy()) {
2315 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2317 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2319 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2321 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2325 // ((A&~B)|(~A&B)) -> A^B
2326 if ((match(C, m_Not(m_Specific(D))) &&
2327 match(B, m_Not(m_Specific(A)))))
2328 return BinaryOperator::CreateXor(A, D);
2329 // ((~B&A)|(~A&B)) -> A^B
2330 if ((match(A, m_Not(m_Specific(D))) &&
2331 match(B, m_Not(m_Specific(C)))))
2332 return BinaryOperator::CreateXor(C, D);
2333 // ((A&~B)|(B&~A)) -> A^B
2334 if ((match(C, m_Not(m_Specific(B))) &&
2335 match(D, m_Not(m_Specific(A)))))
2336 return BinaryOperator::CreateXor(A, B);
2337 // ((~B&A)|(B&~A)) -> A^B
2338 if ((match(A, m_Not(m_Specific(B))) &&
2339 match(D, m_Not(m_Specific(C)))))
2340 return BinaryOperator::CreateXor(C, B);
2342 // ((A|B)&1)|(B&-2) -> (A&1) | B
2343 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2344 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2345 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2346 if (Ret) return Ret;
2348 // (B&-2)|((A|B)&1) -> (A&1) | B
2349 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2350 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2351 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2352 if (Ret) return Ret;
2354 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2355 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2356 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2357 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2358 if (Ret) return Ret;
2360 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2361 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2362 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2363 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2364 if (Ret) return Ret;
2368 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2369 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2370 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2371 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2372 return BinaryOperator::CreateOr(Op0, C);
2374 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2375 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2376 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2377 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2378 return BinaryOperator::CreateOr(Op1, C);
2380 // ((B | C) & A) | B -> B | (A & C)
2381 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2382 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2384 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2387 // Canonicalize xor to the RHS.
2388 bool SwappedForXor = false;
2389 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2390 std::swap(Op0, Op1);
2391 SwappedForXor = true;
2394 // A | ( A ^ B) -> A | B
2395 // A | (~A ^ B) -> A | ~B
2396 // (A & B) | (A ^ B)
2397 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2398 if (Op0 == A || Op0 == B)
2399 return BinaryOperator::CreateOr(A, B);
2401 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2402 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2403 return BinaryOperator::CreateOr(A, B);
2405 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2406 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2407 return BinaryOperator::CreateOr(Not, Op0);
2409 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2410 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2411 return BinaryOperator::CreateOr(Not, Op0);
2415 // A | ~(A | B) -> A | ~B
2416 // A | ~(A ^ B) -> A | ~B
2417 if (match(Op1, m_Not(m_Value(A))))
2418 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2419 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2420 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2421 B->getOpcode() == Instruction::Xor)) {
2422 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2424 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2425 return BinaryOperator::CreateOr(Not, Op0);
2428 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2429 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2430 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2431 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2433 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2434 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2435 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2436 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2439 std::swap(Op0, Op1);
2442 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2443 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2445 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2446 return ReplaceInstUsesWith(I, Res);
2448 // TODO: Make this recursive; it's a little tricky because an arbitrary
2449 // number of 'or' instructions might have to be created.
2451 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2452 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2453 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2454 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2455 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2456 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2457 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2459 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2460 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2461 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2462 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2463 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2464 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2465 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2469 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2470 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2471 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2472 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2473 return ReplaceInstUsesWith(I, Res);
2475 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2476 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2477 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2478 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2479 Type *SrcTy = Op0C->getOperand(0)->getType();
2480 if (SrcTy == Op1C->getOperand(0)->getType() &&
2481 SrcTy->isIntOrIntVectorTy()) {
2482 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2484 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2485 // Only do this if the casts both really cause code to be
2487 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2488 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2489 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2490 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2493 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2494 // cast is otherwise not optimizable. This happens for vector sexts.
2495 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2496 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2497 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2498 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2500 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2501 // cast is otherwise not optimizable. This happens for vector sexts.
2502 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2503 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2504 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2505 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2510 // or(sext(A), B) -> A ? -1 : B where A is an i1
2511 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2512 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2513 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2514 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2515 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2517 // Note: If we've gotten to the point of visiting the outer OR, then the
2518 // inner one couldn't be simplified. If it was a constant, then it won't
2519 // be simplified by a later pass either, so we try swapping the inner/outer
2520 // ORs in the hopes that we'll be able to simplify it this way.
2521 // (X|C) | V --> (X|V) | C
2522 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2523 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2524 Value *Inner = Builder->CreateOr(A, Op1);
2525 Inner->takeName(Op0);
2526 return BinaryOperator::CreateOr(Inner, C1);
2529 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2530 // Since this OR statement hasn't been optimized further yet, we hope
2531 // that this transformation will allow the new ORs to be optimized.
2533 Value *X = nullptr, *Y = nullptr;
2534 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2535 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2536 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2537 Value *orTrue = Builder->CreateOr(A, C);
2538 Value *orFalse = Builder->CreateOr(B, D);
2539 return SelectInst::Create(X, orTrue, orFalse);
2543 return Changed ? &I : nullptr;
2546 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2547 bool Changed = SimplifyAssociativeOrCommutative(I);
2548 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550 if (Value *V = SimplifyVectorOp(I))
2551 return ReplaceInstUsesWith(I, V);
2553 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
2554 return ReplaceInstUsesWith(I, V);
2556 // (A&B)^(A&C) -> A&(B^C) etc
2557 if (Value *V = SimplifyUsingDistributiveLaws(I))
2558 return ReplaceInstUsesWith(I, V);
2560 // See if we can simplify any instructions used by the instruction whose sole
2561 // purpose is to compute bits we don't care about.
2562 if (SimplifyDemandedInstructionBits(I))
2565 if (Value *V = SimplifyBSwap(I))
2566 return ReplaceInstUsesWith(I, V);
2568 // Is this a ~ operation?
2569 if (Value *NotOp = dyn_castNotVal(&I)) {
2570 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2571 if (Op0I->getOpcode() == Instruction::And ||
2572 Op0I->getOpcode() == Instruction::Or) {
2573 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2574 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2575 if (dyn_castNotVal(Op0I->getOperand(1)))
2576 Op0I->swapOperands();
2577 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2579 Builder->CreateNot(Op0I->getOperand(1),
2580 Op0I->getOperand(1)->getName()+".not");
2581 if (Op0I->getOpcode() == Instruction::And)
2582 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2583 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2586 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2587 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2588 if (IsFreeToInvert(Op0I->getOperand(0),
2589 Op0I->getOperand(0)->hasOneUse()) &&
2590 IsFreeToInvert(Op0I->getOperand(1),
2591 Op0I->getOperand(1)->hasOneUse())) {
2593 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2595 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2596 if (Op0I->getOpcode() == Instruction::And)
2597 return BinaryOperator::CreateOr(NotX, NotY);
2598 return BinaryOperator::CreateAnd(NotX, NotY);
2601 } else if (Op0I->getOpcode() == Instruction::AShr) {
2602 // ~(~X >>s Y) --> (X >>s Y)
2603 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2604 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2609 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2610 if (RHS->isAllOnesValue() && Op0->hasOneUse())
2611 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2612 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2613 return CmpInst::Create(CI->getOpcode(),
2614 CI->getInversePredicate(),
2615 CI->getOperand(0), CI->getOperand(1));
2618 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2619 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2620 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2621 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2622 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2623 Instruction::CastOps Opcode = Op0C->getOpcode();
2624 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2625 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2626 Op0C->getDestTy()))) {
2627 CI->setPredicate(CI->getInversePredicate());
2628 return CastInst::Create(Opcode, CI, Op0C->getType());
2634 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2635 // ~(c-X) == X-c-1 == X+(-c-1)
2636 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2637 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2638 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2639 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2640 ConstantInt::get(I.getType(), 1));
2641 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2644 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2645 if (Op0I->getOpcode() == Instruction::Add) {
2646 // ~(X-c) --> (-c-1)-X
2647 if (RHS->isAllOnesValue()) {
2648 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2649 return BinaryOperator::CreateSub(
2650 ConstantExpr::getSub(NegOp0CI,
2651 ConstantInt::get(I.getType(), 1)),
2652 Op0I->getOperand(0));
2653 } else if (RHS->getValue().isSignBit()) {
2654 // (X + C) ^ signbit -> (X + C + signbit)
2655 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2656 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2659 } else if (Op0I->getOpcode() == Instruction::Or) {
2660 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2661 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2663 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2664 // Anything in both C1 and C2 is known to be zero, remove it from
2666 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2667 NewRHS = ConstantExpr::getAnd(NewRHS,
2668 ConstantExpr::getNot(CommonBits));
2670 I.setOperand(0, Op0I->getOperand(0));
2671 I.setOperand(1, NewRHS);
2674 } else if (Op0I->getOpcode() == Instruction::LShr) {
2675 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2679 if (Op0I->hasOneUse() &&
2680 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2681 E1->getOpcode() == Instruction::Xor &&
2682 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2683 // fold (C1 >> C2) ^ C3
2684 ConstantInt *C2 = Op0CI, *C3 = RHS;
2685 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2686 FoldConst ^= C3->getValue();
2687 // Prepare the two operands.
2688 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2689 Opnd0->takeName(Op0I);
2690 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2691 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2693 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2699 // Try to fold constant and into select arguments.
2700 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2701 if (Instruction *R = FoldOpIntoSelect(I, SI))
2703 if (isa<PHINode>(Op0))
2704 if (Instruction *NV = FoldOpIntoPhi(I))
2708 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2711 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2712 if (A == Op0) { // B^(B|A) == (A|B)^B
2713 Op1I->swapOperands();
2715 std::swap(Op0, Op1);
2716 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2717 I.swapOperands(); // Simplified below.
2718 std::swap(Op0, Op1);
2720 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2722 if (A == Op0) { // A^(A&B) -> A^(B&A)
2723 Op1I->swapOperands();
2726 if (B == Op0) { // A^(B&A) -> (B&A)^A
2727 I.swapOperands(); // Simplified below.
2728 std::swap(Op0, Op1);
2733 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2736 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2737 Op0I->hasOneUse()) {
2738 if (A == Op1) // (B|A)^B == (A|B)^B
2740 if (B == Op1) // (A|B)^B == A & ~B
2741 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2742 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2744 if (A == Op1) // (A&B)^A -> (B&A)^A
2746 if (B == Op1 && // (B&A)^A == ~B & A
2747 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2748 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2754 Value *A, *B, *C, *D;
2755 // (A & B)^(A | B) -> A ^ B
2756 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2757 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2758 if ((A == C && B == D) || (A == D && B == C))
2759 return BinaryOperator::CreateXor(A, B);
2761 // (A | B)^(A & B) -> A ^ B
2762 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2763 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2764 if ((A == C && B == D) || (A == D && B == C))
2765 return BinaryOperator::CreateXor(A, B);
2767 // (A | ~B) ^ (~A | B) -> A ^ B
2768 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2769 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2770 return BinaryOperator::CreateXor(A, B);
2772 // (~A | B) ^ (A | ~B) -> A ^ B
2773 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2774 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2775 return BinaryOperator::CreateXor(A, B);
2777 // (A & ~B) ^ (~A & B) -> A ^ B
2778 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2779 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2780 return BinaryOperator::CreateXor(A, B);
2782 // (~A & B) ^ (A & ~B) -> A ^ B
2783 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2784 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2785 return BinaryOperator::CreateXor(A, B);
2787 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2788 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2789 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2791 return BinaryOperator::CreateXor(
2792 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2794 return BinaryOperator::CreateXor(
2795 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2797 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2798 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2799 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2801 return BinaryOperator::CreateXor(
2802 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2804 return BinaryOperator::CreateXor(
2805 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2807 // (A & B) ^ (A ^ B) -> (A | B)
2808 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2809 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2810 return BinaryOperator::CreateOr(A, B);
2811 // (A ^ B) ^ (A & B) -> (A | B)
2812 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2813 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2814 return BinaryOperator::CreateOr(A, B);
2817 Value *A = nullptr, *B = nullptr;
2818 // (A & ~B) ^ (~A) -> ~(A & B)
2819 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2820 match(Op1, m_Not(m_Specific(A))))
2821 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2823 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2824 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2825 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2826 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2827 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2828 LHS->getOperand(1) == RHS->getOperand(0))
2829 LHS->swapOperands();
2830 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2831 LHS->getOperand(1) == RHS->getOperand(1)) {
2832 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2833 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2834 bool isSigned = LHS->isSigned() || RHS->isSigned();
2835 return ReplaceInstUsesWith(I,
2836 getNewICmpValue(isSigned, Code, Op0, Op1,
2841 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2842 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2843 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2844 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2845 Type *SrcTy = Op0C->getOperand(0)->getType();
2846 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2847 // Only do this if the casts both really cause code to be generated.
2848 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2850 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2852 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2853 Op1C->getOperand(0), I.getName());
2854 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2859 return Changed ? &I : nullptr;