79cf288b338034a92f5746b9c78deb038fb0696e
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineAndOrXor.cpp
1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/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"
20 using namespace llvm;
21 using namespace PatternMatch;
22
23 #define DEBUG_TYPE "instcombine"
24
25 /// isFreeToInvert - Return true if the specified value is free to invert (apply
26 /// ~ to).  This happens in cases where the ~ can be eliminated.
27 static inline bool isFreeToInvert(Value *V) {
28   // ~(~(X)) -> X.
29   if (BinaryOperator::isNot(V))
30     return true;
31
32   // Constants can be considered to be not'ed values.
33   if (isa<ConstantInt>(V))
34     return true;
35
36   // Compares can be inverted if they have a single use.
37   if (CmpInst *CI = dyn_cast<CmpInst>(V))
38     return CI->hasOneUse();
39
40   return false;
41 }
42
43 static inline Value *dyn_castNotVal(Value *V) {
44   // If this is not(not(x)) don't return that this is a not: we want the two
45   // not's to be folded first.
46   if (BinaryOperator::isNot(V)) {
47     Value *Operand = BinaryOperator::getNotArgument(V);
48     if (!isFreeToInvert(Operand))
49       return Operand;
50   }
51
52   // Constants can be considered to be not'ed values...
53   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
54     return ConstantInt::get(C->getType(), ~C->getValue());
55   return nullptr;
56 }
57
58 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
59 /// predicate into a three bit mask. It also returns whether it is an ordered
60 /// predicate by reference.
61 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
62   isOrdered = false;
63   switch (CC) {
64   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
65   case FCmpInst::FCMP_UNO:                   return 0;  // 000
66   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
67   case FCmpInst::FCMP_UGT:                   return 1;  // 001
68   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
69   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
70   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
71   case FCmpInst::FCMP_UGE:                   return 3;  // 011
72   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
73   case FCmpInst::FCMP_ULT:                   return 4;  // 100
74   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
75   case FCmpInst::FCMP_UNE:                   return 5;  // 101
76   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
77   case FCmpInst::FCMP_ULE:                   return 6;  // 110
78     // True -> 7
79   default:
80     // Not expecting FCMP_FALSE and FCMP_TRUE;
81     llvm_unreachable("Unexpected FCmp predicate!");
82   }
83 }
84
85 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
86 /// opcode and two operands into either a constant true or false, or a brand
87 /// new ICmp instruction. The sign is passed in to determine which kind
88 /// of predicate to use in the new icmp instruction.
89 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
90                               InstCombiner::BuilderTy *Builder) {
91   ICmpInst::Predicate NewPred;
92   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
93     return NewConstant;
94   return Builder->CreateICmp(NewPred, LHS, RHS);
95 }
96
97 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
98 /// opcode and two operands into either a FCmp instruction. isordered is passed
99 /// in to determine which kind of predicate to use in the new fcmp instruction.
100 static Value *getFCmpValue(bool isordered, unsigned code,
101                            Value *LHS, Value *RHS,
102                            InstCombiner::BuilderTy *Builder) {
103   CmpInst::Predicate Pred;
104   switch (code) {
105   default: llvm_unreachable("Illegal FCmp code!");
106   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
107   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
108   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
109   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
110   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
111   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
112   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
113   case 7:
114     if (!isordered) return ConstantInt::getTrue(LHS->getContext());
115     Pred = FCmpInst::FCMP_ORD; break;
116   }
117   return Builder->CreateFCmp(Pred, LHS, RHS);
118 }
119
120 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
121 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
122 // guaranteed to be a binary operator.
123 Instruction *InstCombiner::OptAndOp(Instruction *Op,
124                                     ConstantInt *OpRHS,
125                                     ConstantInt *AndRHS,
126                                     BinaryOperator &TheAnd) {
127   Value *X = Op->getOperand(0);
128   Constant *Together = nullptr;
129   if (!Op->isShift())
130     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
131
132   switch (Op->getOpcode()) {
133   case Instruction::Xor:
134     if (Op->hasOneUse()) {
135       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
136       Value *And = Builder->CreateAnd(X, AndRHS);
137       And->takeName(Op);
138       return BinaryOperator::CreateXor(And, Together);
139     }
140     break;
141   case Instruction::Or:
142     if (Op->hasOneUse()){
143       if (Together != OpRHS) {
144         // (X | C1) & C2 --> (X | (C1&C2)) & C2
145         Value *Or = Builder->CreateOr(X, Together);
146         Or->takeName(Op);
147         return BinaryOperator::CreateAnd(Or, AndRHS);
148       }
149
150       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
151       if (TogetherCI && !TogetherCI->isZero()){
152         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
153         // NOTE: This reduces the number of bits set in the & mask, which
154         // can expose opportunities for store narrowing.
155         Together = ConstantExpr::getXor(AndRHS, Together);
156         Value *And = Builder->CreateAnd(X, Together);
157         And->takeName(Op);
158         return BinaryOperator::CreateOr(And, OpRHS);
159       }
160     }
161
162     break;
163   case Instruction::Add:
164     if (Op->hasOneUse()) {
165       // Adding a one to a single bit bit-field should be turned into an XOR
166       // of the bit.  First thing to check is to see if this AND is with a
167       // single bit constant.
168       const APInt &AndRHSV = AndRHS->getValue();
169
170       // If there is only one bit set.
171       if (AndRHSV.isPowerOf2()) {
172         // Ok, at this point, we know that we are masking the result of the
173         // ADD down to exactly one bit.  If the constant we are adding has
174         // no bits set below this bit, then we can eliminate the ADD.
175         const APInt& AddRHS = OpRHS->getValue();
176
177         // Check to see if any bits below the one bit set in AndRHSV are set.
178         if ((AddRHS & (AndRHSV-1)) == 0) {
179           // If not, the only thing that can effect the output of the AND is
180           // the bit specified by AndRHSV.  If that bit is set, the effect of
181           // the XOR is to toggle the bit.  If it is clear, then the ADD has
182           // no effect.
183           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
184             TheAnd.setOperand(0, X);
185             return &TheAnd;
186           } else {
187             // Pull the XOR out of the AND.
188             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
189             NewAnd->takeName(Op);
190             return BinaryOperator::CreateXor(NewAnd, AndRHS);
191           }
192         }
193       }
194     }
195     break;
196
197   case Instruction::Shl: {
198     // We know that the AND will not produce any of the bits shifted in, so if
199     // the anded constant includes them, clear them now!
200     //
201     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
202     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
203     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
204     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
205
206     if (CI->getValue() == ShlMask)
207       // Masking out bits that the shift already masks.
208       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
209
210     if (CI != AndRHS) {                  // Reducing bits set in and.
211       TheAnd.setOperand(1, CI);
212       return &TheAnd;
213     }
214     break;
215   }
216   case Instruction::LShr: {
217     // We know that the AND will not produce any of the bits shifted in, so if
218     // the anded constant includes them, clear them now!  This only applies to
219     // unsigned shifts, because a signed shr may bring in set bits!
220     //
221     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
222     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
223     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
224     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
225
226     if (CI->getValue() == ShrMask)
227       // Masking out bits that the shift already masks.
228       return ReplaceInstUsesWith(TheAnd, Op);
229
230     if (CI != AndRHS) {
231       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
232       return &TheAnd;
233     }
234     break;
235   }
236   case Instruction::AShr:
237     // Signed shr.
238     // See if this is shifting in some sign extension, then masking it out
239     // with an and.
240     if (Op->hasOneUse()) {
241       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
242       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
243       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
244       Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
245       if (C == AndRHS) {          // Masking out bits shifted in.
246         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
247         // Make the argument unsigned.
248         Value *ShVal = Op->getOperand(0);
249         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
250         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
251       }
252     }
253     break;
254   }
255   return nullptr;
256 }
257
258 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
259 /// (V < Lo || V >= Hi).  In practice, we emit the more efficient
260 /// (V-Lo) \<u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
261 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
262 /// insert new instructions.
263 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
264                                      bool isSigned, bool Inside) {
265   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
266             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
267          "Lo is not <= Hi in range emission code!");
268
269   if (Inside) {
270     if (Lo == Hi)  // Trivially false.
271       return Builder->getFalse();
272
273     // V >= Min && V < Hi --> V < Hi
274     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
275       ICmpInst::Predicate pred = (isSigned ?
276         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
277       return Builder->CreateICmp(pred, V, Hi);
278     }
279
280     // Emit V-Lo <u Hi-Lo
281     Constant *NegLo = ConstantExpr::getNeg(Lo);
282     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
283     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
284     return Builder->CreateICmpULT(Add, UpperBound);
285   }
286
287   if (Lo == Hi)  // Trivially true.
288     return Builder->getTrue();
289
290   // V < Min || V >= Hi -> V > Hi-1
291   Hi = SubOne(cast<ConstantInt>(Hi));
292   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
293     ICmpInst::Predicate pred = (isSigned ?
294         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
295     return Builder->CreateICmp(pred, V, Hi);
296   }
297
298   // Emit V-Lo >u Hi-1-Lo
299   // Note that Hi has already had one subtracted from it, above.
300   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
301   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
302   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
303   return Builder->CreateICmpUGT(Add, LowerBound);
304 }
305
306 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
307 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
308 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
309 // not, since all 1s are not contiguous.
310 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
311   const APInt& V = Val->getValue();
312   uint32_t BitWidth = Val->getType()->getBitWidth();
313   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
314
315   // look for the first zero bit after the run of ones
316   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
317   // look for the first non-zero bit
318   ME = V.getActiveBits();
319   return true;
320 }
321
322 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
323 /// where isSub determines whether the operator is a sub.  If we can fold one of
324 /// the following xforms:
325 ///
326 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
327 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
328 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
329 ///
330 /// return (A +/- B).
331 ///
332 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
333                                         ConstantInt *Mask, bool isSub,
334                                         Instruction &I) {
335   Instruction *LHSI = dyn_cast<Instruction>(LHS);
336   if (!LHSI || LHSI->getNumOperands() != 2 ||
337       !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
338
339   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
340
341   switch (LHSI->getOpcode()) {
342   default: return nullptr;
343   case Instruction::And:
344     if (ConstantExpr::getAnd(N, Mask) == Mask) {
345       // If the AndRHS is a power of two minus one (0+1+), this is simple.
346       if ((Mask->getValue().countLeadingZeros() +
347            Mask->getValue().countPopulation()) ==
348           Mask->getValue().getBitWidth())
349         break;
350
351       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
352       // part, we don't need any explicit masks to take them out of A.  If that
353       // is all N is, ignore it.
354       uint32_t MB = 0, ME = 0;
355       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
356         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
357         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
358         if (MaskedValueIsZero(RHS, Mask, 0, &I))
359           break;
360       }
361     }
362     return nullptr;
363   case Instruction::Or:
364   case Instruction::Xor:
365     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
366     if ((Mask->getValue().countLeadingZeros() +
367          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
368         && ConstantExpr::getAnd(N, Mask)->isNullValue())
369       break;
370     return nullptr;
371   }
372
373   if (isSub)
374     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
375   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
376 }
377
378 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
379 /// One of A and B is considered the mask, the other the value. This is
380 /// described as the "AMask" or "BMask" part of the enum. If the enum
381 /// contains only "Mask", then both A and B can be considered masks.
382 /// If A is the mask, then it was proven, that (A & C) == C. This
383 /// is trivial if C == A, or C == 0. If both A and C are constants, this
384 /// proof is also easy.
385 /// For the following explanations we assume that A is the mask.
386 /// The part "AllOnes" declares, that the comparison is true only
387 /// if (A & B) == A, or all bits of A are set in B.
388 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
389 /// The part "AllZeroes" declares, that the comparison is true only
390 /// if (A & B) == 0, or all bits of A are cleared in B.
391 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
392 /// The part "Mixed" declares, that (A & B) == C and C might or might not
393 /// contain any number of one bits and zero bits.
394 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
395 /// The Part "Not" means, that in above descriptions "==" should be replaced
396 /// by "!=".
397 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
398 /// If the mask A contains a single bit, then the following is equivalent:
399 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
400 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
401 enum MaskedICmpType {
402   FoldMskICmp_AMask_AllOnes           =     1,
403   FoldMskICmp_AMask_NotAllOnes        =     2,
404   FoldMskICmp_BMask_AllOnes           =     4,
405   FoldMskICmp_BMask_NotAllOnes        =     8,
406   FoldMskICmp_Mask_AllZeroes          =    16,
407   FoldMskICmp_Mask_NotAllZeroes       =    32,
408   FoldMskICmp_AMask_Mixed             =    64,
409   FoldMskICmp_AMask_NotMixed          =   128,
410   FoldMskICmp_BMask_Mixed             =   256,
411   FoldMskICmp_BMask_NotMixed          =   512
412 };
413
414 /// return the set of pattern classes (from MaskedICmpType)
415 /// that (icmp SCC (A & B), C) satisfies
416 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
417                                     ICmpInst::Predicate SCC)
418 {
419   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
420   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
421   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
422   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
423   bool icmp_abit = (ACst && !ACst->isZero() &&
424                     ACst->getValue().isPowerOf2());
425   bool icmp_bbit = (BCst && !BCst->isZero() &&
426                     BCst->getValue().isPowerOf2());
427   unsigned result = 0;
428   if (CCst && CCst->isZero()) {
429     // if C is zero, then both A and B qualify as mask
430     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
431                           FoldMskICmp_Mask_AllZeroes |
432                           FoldMskICmp_AMask_Mixed |
433                           FoldMskICmp_BMask_Mixed)
434                        : (FoldMskICmp_Mask_NotAllZeroes |
435                           FoldMskICmp_Mask_NotAllZeroes |
436                           FoldMskICmp_AMask_NotMixed |
437                           FoldMskICmp_BMask_NotMixed));
438     if (icmp_abit)
439       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
440                             FoldMskICmp_AMask_NotMixed)
441                          : (FoldMskICmp_AMask_AllOnes |
442                             FoldMskICmp_AMask_Mixed));
443     if (icmp_bbit)
444       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
445                             FoldMskICmp_BMask_NotMixed)
446                          : (FoldMskICmp_BMask_AllOnes |
447                             FoldMskICmp_BMask_Mixed));
448     return result;
449   }
450   if (A == C) {
451     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
452                           FoldMskICmp_AMask_Mixed)
453                        : (FoldMskICmp_AMask_NotAllOnes |
454                           FoldMskICmp_AMask_NotMixed));
455     if (icmp_abit)
456       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
457                             FoldMskICmp_AMask_NotMixed)
458                          : (FoldMskICmp_Mask_AllZeroes |
459                             FoldMskICmp_AMask_Mixed));
460   } else if (ACst && CCst &&
461              ConstantExpr::getAnd(ACst, CCst) == CCst) {
462     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
463                        : FoldMskICmp_AMask_NotMixed);
464   }
465   if (B == C) {
466     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
467                           FoldMskICmp_BMask_Mixed)
468                        : (FoldMskICmp_BMask_NotAllOnes |
469                           FoldMskICmp_BMask_NotMixed));
470     if (icmp_bbit)
471       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
472                             FoldMskICmp_BMask_NotMixed)
473                          : (FoldMskICmp_Mask_AllZeroes |
474                             FoldMskICmp_BMask_Mixed));
475   } else if (BCst && CCst &&
476              ConstantExpr::getAnd(BCst, CCst) == CCst) {
477     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
478                        : FoldMskICmp_BMask_NotMixed);
479   }
480   return result;
481 }
482
483 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
484 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
485 /// is adjacent to the corresponding normal flag (recording ==), this just
486 /// involves swapping those bits over.
487 static unsigned conjugateICmpMask(unsigned Mask) {
488   unsigned NewMask;
489   NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
490                      FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
491                      FoldMskICmp_BMask_Mixed))
492             << 1;
493
494   NewMask |=
495       (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
496                FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
497                FoldMskICmp_BMask_NotMixed))
498       >> 1;
499
500   return NewMask;
501 }
502
503 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
504 /// if possible. The returned predicate is either == or !=. Returns false if
505 /// decomposition fails.
506 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
507                                  Value *&X, Value *&Y, Value *&Z) {
508   ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
509   if (!C)
510     return false;
511
512   switch (I->getPredicate()) {
513   default:
514     return false;
515   case ICmpInst::ICMP_SLT:
516     // X < 0 is equivalent to (X & SignBit) != 0.
517     if (!C->isZero())
518       return false;
519     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
520     Pred = ICmpInst::ICMP_NE;
521     break;
522   case ICmpInst::ICMP_SGT:
523     // X > -1 is equivalent to (X & SignBit) == 0.
524     if (!C->isAllOnesValue())
525       return false;
526     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
527     Pred = ICmpInst::ICMP_EQ;
528     break;
529   case ICmpInst::ICMP_ULT:
530     // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
531     if (!C->getValue().isPowerOf2())
532       return false;
533     Y = ConstantInt::get(I->getContext(), -C->getValue());
534     Pred = ICmpInst::ICMP_EQ;
535     break;
536   case ICmpInst::ICMP_UGT:
537     // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
538     if (!(C->getValue() + 1).isPowerOf2())
539       return false;
540     Y = ConstantInt::get(I->getContext(), ~C->getValue());
541     Pred = ICmpInst::ICMP_NE;
542     break;
543   }
544
545   X = I->getOperand(0);
546   Z = ConstantInt::getNullValue(C->getType());
547   return true;
548 }
549
550 /// foldLogOpOfMaskedICmpsHelper:
551 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
552 /// return the set of pattern classes (from MaskedICmpType)
553 /// that both LHS and RHS satisfy
554 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
555                                              Value*& B, Value*& C,
556                                              Value*& D, Value*& E,
557                                              ICmpInst *LHS, ICmpInst *RHS,
558                                              ICmpInst::Predicate &LHSCC,
559                                              ICmpInst::Predicate &RHSCC) {
560   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
561   // vectors are not (yet?) supported
562   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
563
564   // Here comes the tricky part:
565   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
566   // and L11 & L12 == L21 & L22. The same goes for RHS.
567   // Now we must find those components L** and R**, that are equal, so
568   // that we can extract the parameters A, B, C, D, and E for the canonical
569   // above.
570   Value *L1 = LHS->getOperand(0);
571   Value *L2 = LHS->getOperand(1);
572   Value *L11,*L12,*L21,*L22;
573   // Check whether the icmp can be decomposed into a bit test.
574   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
575     L21 = L22 = L1 = nullptr;
576   } else {
577     // Look for ANDs in the LHS icmp.
578     if (!L1->getType()->isIntegerTy()) {
579       // You can icmp pointers, for example. They really aren't masks.
580       L11 = L12 = nullptr;
581     } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
582       // Any icmp can be viewed as being trivially masked; if it allows us to
583       // remove one, it's worth it.
584       L11 = L1;
585       L12 = Constant::getAllOnesValue(L1->getType());
586     }
587
588     if (!L2->getType()->isIntegerTy()) {
589       // You can icmp pointers, for example. They really aren't masks.
590       L21 = L22 = nullptr;
591     } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
592       L21 = L2;
593       L22 = Constant::getAllOnesValue(L2->getType());
594     }
595   }
596
597   // Bail if LHS was a icmp that can't be decomposed into an equality.
598   if (!ICmpInst::isEquality(LHSCC))
599     return 0;
600
601   Value *R1 = RHS->getOperand(0);
602   Value *R2 = RHS->getOperand(1);
603   Value *R11,*R12;
604   bool ok = false;
605   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
606     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
607       A = R11; D = R12;
608     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
609       A = R12; D = R11;
610     } else {
611       return 0;
612     }
613     E = R2; R1 = nullptr; ok = true;
614   } else if (R1->getType()->isIntegerTy()) {
615     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
616       // As before, model no mask as a trivial mask if it'll let us do an
617       // optimization.
618       R11 = R1;
619       R12 = Constant::getAllOnesValue(R1->getType());
620     }
621
622     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
623       A = R11; D = R12; E = R2; ok = true;
624     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
625       A = R12; D = R11; E = R2; ok = true;
626     }
627   }
628
629   // Bail if RHS was a icmp that can't be decomposed into an equality.
630   if (!ICmpInst::isEquality(RHSCC))
631     return 0;
632
633   // Look for ANDs in on the right side of the RHS icmp.
634   if (!ok && R2->getType()->isIntegerTy()) {
635     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
636       R11 = R2;
637       R12 = Constant::getAllOnesValue(R2->getType());
638     }
639
640     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
641       A = R11; D = R12; E = R1; ok = true;
642     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
643       A = R12; D = R11; E = R1; ok = true;
644     } else {
645       return 0;
646     }
647   }
648   if (!ok)
649     return 0;
650
651   if (L11 == A) {
652     B = L12; C = L2;
653   } else if (L12 == A) {
654     B = L11; C = L2;
655   } else if (L21 == A) {
656     B = L22; C = L1;
657   } else if (L22 == A) {
658     B = L21; C = L1;
659   }
660
661   unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
662   unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
663   return left_type & right_type;
664 }
665 /// foldLogOpOfMaskedICmps:
666 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
667 /// into a single (icmp(A & X) ==/!= Y)
668 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
669                                      llvm::InstCombiner::BuilderTy* Builder) {
670   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
671   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
672   unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
673                                                LHSCC, RHSCC);
674   if (mask == 0) return nullptr;
675   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
676          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
677
678   // In full generality:
679   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
680   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
681   //
682   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
683   // equivalent to (icmp (A & X) !Op Y).
684   //
685   // Therefore, we can pretend for the rest of this function that we're dealing
686   // with the conjunction, provided we flip the sense of any comparisons (both
687   // input and output).
688
689   // In most cases we're going to produce an EQ for the "&&" case.
690   ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
691   if (!IsAnd) {
692     // Convert the masking analysis into its equivalent with negated
693     // comparisons.
694     mask = conjugateICmpMask(mask);
695   }
696
697   if (mask & FoldMskICmp_Mask_AllZeroes) {
698     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
699     // -> (icmp eq (A & (B|D)), 0)
700     Value* newOr = Builder->CreateOr(B, D);
701     Value* newAnd = Builder->CreateAnd(A, newOr);
702     // we can't use C as zero, because we might actually handle
703     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
704     // with B and D, having a single bit set
705     Value* zero = Constant::getNullValue(A->getType());
706     return Builder->CreateICmp(NEWCC, newAnd, zero);
707   }
708   if (mask & FoldMskICmp_BMask_AllOnes) {
709     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
710     // -> (icmp eq (A & (B|D)), (B|D))
711     Value* newOr = Builder->CreateOr(B, D);
712     Value* newAnd = Builder->CreateAnd(A, newOr);
713     return Builder->CreateICmp(NEWCC, newAnd, newOr);
714   }
715   if (mask & FoldMskICmp_AMask_AllOnes) {
716     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
717     // -> (icmp eq (A & (B&D)), A)
718     Value* newAnd1 = Builder->CreateAnd(B, D);
719     Value* newAnd = Builder->CreateAnd(A, newAnd1);
720     return Builder->CreateICmp(NEWCC, newAnd, A);
721   }
722
723   // Remaining cases assume at least that B and D are constant, and depend on
724   // their actual values. This isn't strictly, necessary, just a "handle the
725   // easy cases for now" decision.
726   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
727   if (!BCst) return nullptr;
728   ConstantInt *DCst = dyn_cast<ConstantInt>(D);
729   if (!DCst) return nullptr;
730
731   if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
732     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
733     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
734     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
735     // Only valid if one of the masks is a superset of the other (check "B&D" is
736     // the same as either B or D).
737     APInt NewMask = BCst->getValue() & DCst->getValue();
738
739     if (NewMask == BCst->getValue())
740       return LHS;
741     else if (NewMask == DCst->getValue())
742       return RHS;
743   }
744   if (mask & FoldMskICmp_AMask_NotAllOnes) {
745     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
746     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
747     // Only valid if one of the masks is a superset of the other (check "B|D" is
748     // the same as either B or D).
749     APInt NewMask = BCst->getValue() | DCst->getValue();
750
751     if (NewMask == BCst->getValue())
752       return LHS;
753     else if (NewMask == DCst->getValue())
754       return RHS;
755   }
756   if (mask & FoldMskICmp_BMask_Mixed) {
757     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
758     // We already know that B & C == C && D & E == E.
759     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
760     // C and E, which are shared by both the mask B and the mask D, don't
761     // contradict, then we can transform to
762     // -> (icmp eq (A & (B|D)), (C|E))
763     // Currently, we only handle the case of B, C, D, and E being constant.
764     // we can't simply use C and E, because we might actually handle
765     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
766     // with B and D, having a single bit set
767     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
768     if (!CCst) return nullptr;
769     if (LHSCC != NEWCC)
770       CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
771     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
772     if (!ECst) return nullptr;
773     if (RHSCC != NEWCC)
774       ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
775     ConstantInt* MCst = dyn_cast<ConstantInt>(
776       ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
777                            ConstantExpr::getXor(CCst, ECst)) );
778     // if there is a conflict we should actually return a false for the
779     // whole construct
780     if (!MCst->isZero())
781       return nullptr;
782     Value *newOr1 = Builder->CreateOr(B, D);
783     Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
784     Value *newAnd = Builder->CreateAnd(A, newOr1);
785     return Builder->CreateICmp(NEWCC, newAnd, newOr2);
786   }
787   return nullptr;
788 }
789
790 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
791 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
792   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
793
794   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
795   if (PredicatesFoldable(LHSCC, RHSCC)) {
796     if (LHS->getOperand(0) == RHS->getOperand(1) &&
797         LHS->getOperand(1) == RHS->getOperand(0))
798       LHS->swapOperands();
799     if (LHS->getOperand(0) == RHS->getOperand(0) &&
800         LHS->getOperand(1) == RHS->getOperand(1)) {
801       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
802       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
803       bool isSigned = LHS->isSigned() || RHS->isSigned();
804       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
805     }
806   }
807
808   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
809   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
810     return V;
811
812   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
813   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
814   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
815   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
816   if (!LHSCst || !RHSCst) return nullptr;
817
818   if (LHSCst == RHSCst && LHSCC == RHSCC) {
819     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
820     // where C is a power of 2
821     if (LHSCC == ICmpInst::ICMP_ULT &&
822         LHSCst->getValue().isPowerOf2()) {
823       Value *NewOr = Builder->CreateOr(Val, Val2);
824       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
825     }
826
827     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
828     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
829       Value *NewOr = Builder->CreateOr(Val, Val2);
830       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
831     }
832   }
833
834   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
835   // where CMAX is the all ones value for the truncated type,
836   // iff the lower bits of C2 and CA are zero.
837   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
838       LHS->hasOneUse() && RHS->hasOneUse()) {
839     Value *V;
840     ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
841
842     // (trunc x) == C1 & (and x, CA) == C2
843     // (and x, CA) == C2 & (trunc x) == C1
844     if (match(Val2, m_Trunc(m_Value(V))) &&
845         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
846       SmallCst = RHSCst;
847       BigCst = LHSCst;
848     } else if (match(Val, m_Trunc(m_Value(V))) &&
849                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
850       SmallCst = LHSCst;
851       BigCst = RHSCst;
852     }
853
854     if (SmallCst && BigCst) {
855       unsigned BigBitSize = BigCst->getType()->getBitWidth();
856       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
857
858       // Check that the low bits are zero.
859       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
860       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
861         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
862         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
863         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
864         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
865       }
866     }
867   }
868
869   // From here on, we only handle:
870   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
871   if (Val != Val2) return nullptr;
872
873   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
874   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
875       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
876       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
877       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
878     return nullptr;
879
880   // Make a constant range that's the intersection of the two icmp ranges.
881   // If the intersection is empty, we know that the result is false.
882   ConstantRange LHSRange =
883     ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
884   ConstantRange RHSRange =
885     ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
886
887   if (LHSRange.intersectWith(RHSRange).isEmptySet())
888     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
889
890   // We can't fold (ugt x, C) & (sgt x, C2).
891   if (!PredicatesFoldable(LHSCC, RHSCC))
892     return nullptr;
893
894   // Ensure that the larger constant is on the RHS.
895   bool ShouldSwap;
896   if (CmpInst::isSigned(LHSCC) ||
897       (ICmpInst::isEquality(LHSCC) &&
898        CmpInst::isSigned(RHSCC)))
899     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
900   else
901     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
902
903   if (ShouldSwap) {
904     std::swap(LHS, RHS);
905     std::swap(LHSCst, RHSCst);
906     std::swap(LHSCC, RHSCC);
907   }
908
909   // At this point, we know we have two icmp instructions
910   // comparing a value against two constants and and'ing the result
911   // together.  Because of the above check, we know that we only have
912   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
913   // (from the icmp folding check above), that the two constants
914   // are not equal and that the larger constant is on the RHS
915   assert(LHSCst != RHSCst && "Compares not folded above?");
916
917   switch (LHSCC) {
918   default: llvm_unreachable("Unknown integer condition code!");
919   case ICmpInst::ICMP_EQ:
920     switch (RHSCC) {
921     default: llvm_unreachable("Unknown integer condition code!");
922     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
923     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
924     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
925       return LHS;
926     }
927   case ICmpInst::ICMP_NE:
928     switch (RHSCC) {
929     default: llvm_unreachable("Unknown integer condition code!");
930     case ICmpInst::ICMP_ULT:
931       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
932         return Builder->CreateICmpULT(Val, LHSCst);
933       if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
934         return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
935       break;                        // (X != 13 & X u< 15) -> no change
936     case ICmpInst::ICMP_SLT:
937       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
938         return Builder->CreateICmpSLT(Val, LHSCst);
939       break;                        // (X != 13 & X s< 15) -> no change
940     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
941     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
942     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
943       return RHS;
944     case ICmpInst::ICMP_NE:
945       // Special case to get the ordering right when the values wrap around
946       // zero.
947       if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
948         std::swap(LHSCst, RHSCst);
949       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
950         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
951         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
952         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
953                                       Val->getName()+".cmp");
954       }
955       break;                        // (X != 13 & X != 15) -> no change
956     }
957     break;
958   case ICmpInst::ICMP_ULT:
959     switch (RHSCC) {
960     default: llvm_unreachable("Unknown integer condition code!");
961     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
962     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
963       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
964     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
965       break;
966     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
967     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
968       return LHS;
969     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
970       break;
971     }
972     break;
973   case ICmpInst::ICMP_SLT:
974     switch (RHSCC) {
975     default: llvm_unreachable("Unknown integer condition code!");
976     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
977       break;
978     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
979     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
980       return LHS;
981     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
982       break;
983     }
984     break;
985   case ICmpInst::ICMP_UGT:
986     switch (RHSCC) {
987     default: llvm_unreachable("Unknown integer condition code!");
988     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
989     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
990       return RHS;
991     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
992       break;
993     case ICmpInst::ICMP_NE:
994       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
995         return Builder->CreateICmp(LHSCC, Val, RHSCst);
996       break;                        // (X u> 13 & X != 15) -> no change
997     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
998       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
999     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
1000       break;
1001     }
1002     break;
1003   case ICmpInst::ICMP_SGT:
1004     switch (RHSCC) {
1005     default: llvm_unreachable("Unknown integer condition code!");
1006     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
1007     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
1008       return RHS;
1009     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
1010       break;
1011     case ICmpInst::ICMP_NE:
1012       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1013         return Builder->CreateICmp(LHSCC, Val, RHSCst);
1014       break;                        // (X s> 13 & X != 15) -> no change
1015     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
1016       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1017     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
1018       break;
1019     }
1020     break;
1021   }
1022
1023   return nullptr;
1024 }
1025
1026 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
1027 /// instcombine, this returns a Value which should already be inserted into the
1028 /// function.
1029 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1030   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1031       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1032     if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1033       return nullptr;
1034
1035     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
1036     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1037       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1038         // If either of the constants are nans, then the whole thing returns
1039         // false.
1040         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1041           return Builder->getFalse();
1042         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1043       }
1044
1045     // Handle vector zeros.  This occurs because the canonical form of
1046     // "fcmp ord x,x" is "fcmp ord x, 0".
1047     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1048         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1049       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1050     return nullptr;
1051   }
1052
1053   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1054   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1055   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1056
1057
1058   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1059     // Swap RHS operands to match LHS.
1060     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1061     std::swap(Op1LHS, Op1RHS);
1062   }
1063
1064   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1065     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1066     if (Op0CC == Op1CC)
1067       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1068     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1069       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1070     if (Op0CC == FCmpInst::FCMP_TRUE)
1071       return RHS;
1072     if (Op1CC == FCmpInst::FCMP_TRUE)
1073       return LHS;
1074
1075     bool Op0Ordered;
1076     bool Op1Ordered;
1077     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1078     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1079     // uno && ord -> false
1080     if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1081         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1082     if (Op1Pred == 0) {
1083       std::swap(LHS, RHS);
1084       std::swap(Op0Pred, Op1Pred);
1085       std::swap(Op0Ordered, Op1Ordered);
1086     }
1087     if (Op0Pred == 0) {
1088       // uno && ueq -> uno && (uno || eq) -> uno
1089       // ord && olt -> ord && (ord && lt) -> olt
1090       if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1091         return LHS;
1092       if (Op0Ordered && (Op0Ordered == Op1Ordered))
1093         return RHS;
1094
1095       // uno && oeq -> uno && (ord && eq) -> false
1096       if (!Op0Ordered)
1097         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1098       // ord && ueq -> ord && (uno || eq) -> oeq
1099       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1100     }
1101   }
1102
1103   return nullptr;
1104 }
1105
1106 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1107   bool Changed = SimplifyAssociativeOrCommutative(I);
1108   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1109
1110   if (Value *V = SimplifyVectorOp(I))
1111     return ReplaceInstUsesWith(I, V);
1112
1113   if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AT))
1114     return ReplaceInstUsesWith(I, V);
1115
1116   // (A|B)&(A|C) -> A|(B&C) etc
1117   if (Value *V = SimplifyUsingDistributiveLaws(I))
1118     return ReplaceInstUsesWith(I, V);
1119
1120   // See if we can simplify any instructions used by the instruction whose sole
1121   // purpose is to compute bits we don't care about.
1122   if (SimplifyDemandedInstructionBits(I))
1123     return &I;
1124
1125   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1126     const APInt &AndRHSMask = AndRHS->getValue();
1127
1128     // Optimize a variety of ((val OP C1) & C2) combinations...
1129     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1130       Value *Op0LHS = Op0I->getOperand(0);
1131       Value *Op0RHS = Op0I->getOperand(1);
1132       switch (Op0I->getOpcode()) {
1133       default: break;
1134       case Instruction::Xor:
1135       case Instruction::Or: {
1136         // If the mask is only needed on one incoming arm, push it up.
1137         if (!Op0I->hasOneUse()) break;
1138
1139         APInt NotAndRHS(~AndRHSMask);
1140         if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1141           // Not masking anything out for the LHS, move to RHS.
1142           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1143                                              Op0RHS->getName()+".masked");
1144           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1145         }
1146         if (!isa<Constant>(Op0RHS) &&
1147             MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1148           // Not masking anything out for the RHS, move to LHS.
1149           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1150                                              Op0LHS->getName()+".masked");
1151           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1152         }
1153
1154         break;
1155       }
1156       case Instruction::Add:
1157         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1158         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1159         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1160         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1161           return BinaryOperator::CreateAnd(V, AndRHS);
1162         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1163           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1164         break;
1165
1166       case Instruction::Sub:
1167         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1168         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1169         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1170         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1171           return BinaryOperator::CreateAnd(V, AndRHS);
1172
1173         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1174         // has 1's for all bits that the subtraction with A might affect.
1175         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1176           uint32_t BitWidth = AndRHSMask.getBitWidth();
1177           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1178           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1179
1180           if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
1181             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1182             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1183           }
1184         }
1185         break;
1186
1187       case Instruction::Shl:
1188       case Instruction::LShr:
1189         // (1 << x) & 1 --> zext(x == 0)
1190         // (1 >> x) & 1 --> zext(x == 0)
1191         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1192           Value *NewICmp =
1193             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1194           return new ZExtInst(NewICmp, I.getType());
1195         }
1196         break;
1197       }
1198
1199       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1200         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1201           return Res;
1202     }
1203
1204     // If this is an integer truncation, and if the source is an 'and' with
1205     // immediate, transform it.  This frequently occurs for bitfield accesses.
1206     {
1207       Value *X = nullptr; ConstantInt *YC = nullptr;
1208       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1209         // Change: and (trunc (and X, YC) to T), C2
1210         // into  : and (trunc X to T), trunc(YC) & C2
1211         // This will fold the two constants together, which may allow
1212         // other simplifications.
1213         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1214         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1215         C3 = ConstantExpr::getAnd(C3, AndRHS);
1216         return BinaryOperator::CreateAnd(NewCast, C3);
1217       }
1218     }
1219
1220     // Try to fold constant and into select arguments.
1221     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1222       if (Instruction *R = FoldOpIntoSelect(I, SI))
1223         return R;
1224     if (isa<PHINode>(Op0))
1225       if (Instruction *NV = FoldOpIntoPhi(I))
1226         return NV;
1227   }
1228
1229
1230   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1231   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1232     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1233       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1234         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1235                                       I.getName()+".demorgan");
1236         return BinaryOperator::CreateNot(Or);
1237       }
1238
1239   {
1240     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1241     // (A|B) & ~(A&B) -> A^B
1242     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1243         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1244         ((A == C && B == D) || (A == D && B == C)))
1245       return BinaryOperator::CreateXor(A, B);
1246
1247     // ~(A&B) & (A|B) -> A^B
1248     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1249         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1250         ((A == C && B == D) || (A == D && B == C)))
1251       return BinaryOperator::CreateXor(A, B);
1252
1253     // A&(A^B) => A & ~B
1254     {
1255       Value *tmpOp0 = Op0;
1256       Value *tmpOp1 = Op1;
1257       if (Op0->hasOneUse() &&
1258           match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1259         if (A == Op1 || B == Op1 ) {
1260           tmpOp1 = Op0;
1261           tmpOp0 = Op1;
1262           // Simplify below
1263         }
1264       }
1265
1266       if (tmpOp1->hasOneUse() &&
1267           match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1268         if (B == tmpOp0) {
1269           std::swap(A, B);
1270         }
1271         // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1272         // A is originally -1 (or a vector of -1 and undefs), then we enter
1273         // an endless loop. By checking that A is non-constant we ensure that
1274         // we will never get to the loop.
1275         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1276           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1277       }
1278     }
1279
1280     // (A&((~A)|B)) -> A&B
1281     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1282         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1283       return BinaryOperator::CreateAnd(A, Op1);
1284     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1285         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1286       return BinaryOperator::CreateAnd(A, Op0);
1287
1288     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1289     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1290       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1291         if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1292           return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1293
1294     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1295     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1296       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1297         if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1298           return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1299
1300     // (A | B) & ((~A) ^ B) -> (A & B)
1301     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1302         match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1303       return BinaryOperator::CreateAnd(A, B);
1304
1305     // ((~A) ^ B) & (A | B) -> (A & B)
1306     if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1307         match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1308       return BinaryOperator::CreateAnd(A, B);
1309   }
1310
1311   {
1312     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1313     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1314     if (LHS && RHS)
1315       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1316         return ReplaceInstUsesWith(I, Res);
1317
1318     // TODO: Make this recursive; it's a little tricky because an arbitrary
1319     // number of 'and' instructions might have to be created.
1320     Value *X, *Y;
1321     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1322       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1323         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1324           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1325       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1326         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1327           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1328     }
1329     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1330       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1331         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1332           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1333       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1334         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1335           return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1336     }
1337   }
1338
1339   // If and'ing two fcmp, try combine them into one.
1340   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1341     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1342       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1343         return ReplaceInstUsesWith(I, Res);
1344
1345
1346   // fold (and (cast A), (cast B)) -> (cast (and A, B))
1347   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1348     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1349       Type *SrcTy = Op0C->getOperand(0)->getType();
1350       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1351           SrcTy == Op1C->getOperand(0)->getType() &&
1352           SrcTy->isIntOrIntVectorTy()) {
1353         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1354
1355         // Only do this if the casts both really cause code to be generated.
1356         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1357             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1358           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1359           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1360         }
1361
1362         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1363         // cast is otherwise not optimizable.  This happens for vector sexts.
1364         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1365           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1366             if (Value *Res = FoldAndOfICmps(LHS, RHS))
1367               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1368
1369         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1370         // cast is otherwise not optimizable.  This happens for vector sexts.
1371         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1372           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1373             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1374               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1375       }
1376     }
1377
1378   {
1379     Value *X = nullptr;
1380     bool OpsSwapped = false;
1381     // Canonicalize SExt or Not to the LHS
1382     if (match(Op1, m_SExt(m_Value())) ||
1383         match(Op1, m_Not(m_Value()))) {
1384       std::swap(Op0, Op1);
1385       OpsSwapped = true;
1386     }
1387
1388     // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1389     if (match(Op0, m_SExt(m_Value(X))) &&
1390         X->getType()->getScalarType()->isIntegerTy(1)) {
1391       Value *Zero = Constant::getNullValue(Op1->getType());
1392       return SelectInst::Create(X, Op1, Zero);
1393     }
1394
1395     // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1396     if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1397         X->getType()->getScalarType()->isIntegerTy(1)) {
1398       Value *Zero = Constant::getNullValue(Op0->getType());
1399       return SelectInst::Create(X, Zero, Op1);
1400     }
1401
1402     if (OpsSwapped)
1403       std::swap(Op0, Op1);
1404   }
1405
1406   return Changed ? &I : nullptr;
1407 }
1408
1409 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1410 /// capable of providing pieces of a bswap.  The subexpression provides pieces
1411 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1412 /// the expression came from the corresponding "byte swapped" byte in some other
1413 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
1414 /// we know that the expression deposits the low byte of %X into the high byte
1415 /// of the bswap result and that all other bytes are zero.  This expression is
1416 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1417 /// match.
1418 ///
1419 /// This function returns true if the match was unsuccessful and false if so.
1420 /// On entry to the function the "OverallLeftShift" is a signed integer value
1421 /// indicating the number of bytes that the subexpression is later shifted.  For
1422 /// example, if the expression is later right shifted by 16 bits, the
1423 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
1424 /// byte of ByteValues is actually being set.
1425 ///
1426 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1427 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
1428 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
1429 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
1430 /// always in the local (OverallLeftShift) coordinate space.
1431 ///
1432 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1433                               SmallVectorImpl<Value *> &ByteValues) {
1434   if (Instruction *I = dyn_cast<Instruction>(V)) {
1435     // If this is an or instruction, it may be an inner node of the bswap.
1436     if (I->getOpcode() == Instruction::Or) {
1437       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1438                                ByteValues) ||
1439              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1440                                ByteValues);
1441     }
1442
1443     // If this is a logical shift by a constant multiple of 8, recurse with
1444     // OverallLeftShift and ByteMask adjusted.
1445     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1446       unsigned ShAmt =
1447         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1448       // Ensure the shift amount is defined and of a byte value.
1449       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1450         return true;
1451
1452       unsigned ByteShift = ShAmt >> 3;
1453       if (I->getOpcode() == Instruction::Shl) {
1454         // X << 2 -> collect(X, +2)
1455         OverallLeftShift += ByteShift;
1456         ByteMask >>= ByteShift;
1457       } else {
1458         // X >>u 2 -> collect(X, -2)
1459         OverallLeftShift -= ByteShift;
1460         ByteMask <<= ByteShift;
1461         ByteMask &= (~0U >> (32-ByteValues.size()));
1462       }
1463
1464       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1465       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1466
1467       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1468                                ByteValues);
1469     }
1470
1471     // If this is a logical 'and' with a mask that clears bytes, clear the
1472     // corresponding bytes in ByteMask.
1473     if (I->getOpcode() == Instruction::And &&
1474         isa<ConstantInt>(I->getOperand(1))) {
1475       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1476       unsigned NumBytes = ByteValues.size();
1477       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1478       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1479
1480       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1481         // If this byte is masked out by a later operation, we don't care what
1482         // the and mask is.
1483         if ((ByteMask & (1 << i)) == 0)
1484           continue;
1485
1486         // If the AndMask is all zeros for this byte, clear the bit.
1487         APInt MaskB = AndMask & Byte;
1488         if (MaskB == 0) {
1489           ByteMask &= ~(1U << i);
1490           continue;
1491         }
1492
1493         // If the AndMask is not all ones for this byte, it's not a bytezap.
1494         if (MaskB != Byte)
1495           return true;
1496
1497         // Otherwise, this byte is kept.
1498       }
1499
1500       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1501                                ByteValues);
1502     }
1503   }
1504
1505   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1506   // the input value to the bswap.  Some observations: 1) if more than one byte
1507   // is demanded from this input, then it could not be successfully assembled
1508   // into a byteswap.  At least one of the two bytes would not be aligned with
1509   // their ultimate destination.
1510   if (!isPowerOf2_32(ByteMask)) return true;
1511   unsigned InputByteNo = countTrailingZeros(ByteMask);
1512
1513   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1514   // is demanded, it needs to go into byte 0 of the result.  This means that the
1515   // byte needs to be shifted until it lands in the right byte bucket.  The
1516   // shift amount depends on the position: if the byte is coming from the high
1517   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1518   // low part, it must be shifted left.
1519   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1520   if (ByteValues.size()-1-DestByteNo != InputByteNo)
1521     return true;
1522
1523   // If the destination byte value is already defined, the values are or'd
1524   // together, which isn't a bswap (unless it's an or of the same bits).
1525   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1526     return true;
1527   ByteValues[DestByteNo] = V;
1528   return false;
1529 }
1530
1531 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1532 /// If so, insert the new bswap intrinsic and return it.
1533 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1534   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1535   if (!ITy || ITy->getBitWidth() % 16 ||
1536       // ByteMask only allows up to 32-byte values.
1537       ITy->getBitWidth() > 32*8)
1538     return nullptr;   // Can only bswap pairs of bytes.  Can't do vectors.
1539
1540   /// ByteValues - For each byte of the result, we keep track of which value
1541   /// defines each byte.
1542   SmallVector<Value*, 8> ByteValues;
1543   ByteValues.resize(ITy->getBitWidth()/8);
1544
1545   // Try to find all the pieces corresponding to the bswap.
1546   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1547   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1548     return nullptr;
1549
1550   // Check to see if all of the bytes come from the same value.
1551   Value *V = ByteValues[0];
1552   if (!V) return nullptr;  // Didn't find a byte?  Must be zero.
1553
1554   // Check to make sure that all of the bytes come from the same value.
1555   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1556     if (ByteValues[i] != V)
1557       return nullptr;
1558   Module *M = I.getParent()->getParent()->getParent();
1559   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1560   return CallInst::Create(F, V);
1561 }
1562
1563 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1564 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1565 /// we can simplify this expression to "cond ? C : D or B".
1566 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1567                                          Value *C, Value *D) {
1568   // If A is not a select of -1/0, this cannot match.
1569   Value *Cond = nullptr;
1570   if (!match(A, m_SExt(m_Value(Cond))) ||
1571       !Cond->getType()->isIntegerTy(1))
1572     return nullptr;
1573
1574   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1575   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1576     return SelectInst::Create(Cond, C, B);
1577   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1578     return SelectInst::Create(Cond, C, B);
1579
1580   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1581   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1582     return SelectInst::Create(Cond, C, D);
1583   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1584     return SelectInst::Create(Cond, C, D);
1585   return nullptr;
1586 }
1587
1588 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1589 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1590                                    Instruction *CxtI) {
1591   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1592
1593   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
1594   // if K1 and K2 are a one-bit mask.
1595   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1596   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1597
1598   if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1599       RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1600
1601     BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1602     BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1603     if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1604         LAnd->getOpcode() == Instruction::And &&
1605         RAnd->getOpcode() == Instruction::And) {
1606
1607       Value *Mask = nullptr;
1608       Value *Masked = nullptr;
1609       if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1610           isKnownToBeAPowerOfTwo(LAnd->getOperand(1), false, 0, AT, CxtI, DT) &&
1611           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), false, 0, AT, CxtI, DT)) {
1612         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1613         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1614       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1615                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0),
1616                                         false, 0, AT, CxtI, DT) &&
1617                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0),
1618                                         false, 0, AT, CxtI, DT)) {
1619         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1620         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1621       }
1622
1623       if (Masked)
1624         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1625     }
1626   }
1627
1628   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1629   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1630   // The original condition actually refers to the following two ranges:
1631   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1632   // We can fold these two ranges if:
1633   // 1) C1 and C2 is unsigned greater than C3.
1634   // 2) The two ranges are separated.
1635   // 3) C1 ^ C2 is one-bit mask.
1636   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1637   // This implies all values in the two ranges differ by exactly one bit.
1638
1639   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1640       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1641       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1642       LHSCst->getValue() == (RHSCst->getValue())) {
1643
1644     Value *LAdd = LHS->getOperand(0);
1645     Value *RAdd = RHS->getOperand(0);
1646
1647     Value *LAddOpnd, *RAddOpnd;
1648     ConstantInt *LAddCst, *RAddCst;
1649     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1650         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1651         LAddCst->getValue().ugt(LHSCst->getValue()) &&
1652         RAddCst->getValue().ugt(LHSCst->getValue())) {
1653
1654       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1655       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1656         ConstantInt *MaxAddCst = nullptr;
1657         if (LAddCst->getValue().ult(RAddCst->getValue()))
1658           MaxAddCst = RAddCst;
1659         else
1660           MaxAddCst = LAddCst;
1661
1662         APInt RRangeLow = -RAddCst->getValue();
1663         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1664         APInt LRangeLow = -LAddCst->getValue();
1665         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1666         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1667         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1668         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1669                                                    : RRangeLow - LRangeLow;
1670
1671         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1672             RangeDiff.ugt(LHSCst->getValue())) {
1673           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1674
1675           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1676           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1677           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1678         }
1679       }
1680     }
1681   }
1682
1683   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1684   if (PredicatesFoldable(LHSCC, RHSCC)) {
1685     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1686         LHS->getOperand(1) == RHS->getOperand(0))
1687       LHS->swapOperands();
1688     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1689         LHS->getOperand(1) == RHS->getOperand(1)) {
1690       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1691       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1692       bool isSigned = LHS->isSigned() || RHS->isSigned();
1693       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1694     }
1695   }
1696
1697   // handle (roughly):
1698   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1699   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1700     return V;
1701
1702   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1703   if (LHS->hasOneUse() || RHS->hasOneUse()) {
1704     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1705     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1706     Value *A = nullptr, *B = nullptr;
1707     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1708       B = Val;
1709       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1710         A = Val2;
1711       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1712         A = RHS->getOperand(1);
1713     }
1714     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1715     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1716     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1717       B = Val2;
1718       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1719         A = Val;
1720       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1721         A = LHS->getOperand(1);
1722     }
1723     if (A && B)
1724       return Builder->CreateICmp(
1725           ICmpInst::ICMP_UGE,
1726           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1727   }
1728
1729   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1730   if (!LHSCst || !RHSCst) return nullptr;
1731
1732   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1733     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1734     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1735       Value *NewOr = Builder->CreateOr(Val, Val2);
1736       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1737     }
1738   }
1739
1740   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1741   //   iff C2 + CA == C1.
1742   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1743     ConstantInt *AddCst;
1744     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1745       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1746         return Builder->CreateICmpULE(Val, LHSCst);
1747   }
1748
1749   // From here on, we only handle:
1750   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1751   if (Val != Val2) return nullptr;
1752
1753   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1754   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1755       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1756       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1757       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1758     return nullptr;
1759
1760   // We can't fold (ugt x, C) | (sgt x, C2).
1761   if (!PredicatesFoldable(LHSCC, RHSCC))
1762     return nullptr;
1763
1764   // Ensure that the larger constant is on the RHS.
1765   bool ShouldSwap;
1766   if (CmpInst::isSigned(LHSCC) ||
1767       (ICmpInst::isEquality(LHSCC) &&
1768        CmpInst::isSigned(RHSCC)))
1769     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1770   else
1771     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1772
1773   if (ShouldSwap) {
1774     std::swap(LHS, RHS);
1775     std::swap(LHSCst, RHSCst);
1776     std::swap(LHSCC, RHSCC);
1777   }
1778
1779   // At this point, we know we have two icmp instructions
1780   // comparing a value against two constants and or'ing the result
1781   // together.  Because of the above check, we know that we only have
1782   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1783   // icmp folding check above), that the two constants are not
1784   // equal.
1785   assert(LHSCst != RHSCst && "Compares not folded above?");
1786
1787   switch (LHSCC) {
1788   default: llvm_unreachable("Unknown integer condition code!");
1789   case ICmpInst::ICMP_EQ:
1790     switch (RHSCC) {
1791     default: llvm_unreachable("Unknown integer condition code!");
1792     case ICmpInst::ICMP_EQ:
1793       if (LHS->getOperand(0) == RHS->getOperand(0)) {
1794         // if LHSCst and RHSCst differ only by one bit:
1795         // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1796         assert(LHSCst->getValue().ule(LHSCst->getValue()));
1797
1798         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1799         if (Xor.isPowerOf2()) {
1800           Value *NegCst = Builder->getInt(~Xor);
1801           Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1802           return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1803         }
1804       }
1805
1806       if (LHSCst == SubOne(RHSCst)) {
1807         // (X == 13 | X == 14) -> X-13 <u 2
1808         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1809         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1810         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1811         return Builder->CreateICmpULT(Add, AddCST);
1812       }
1813
1814       break;                         // (X == 13 | X == 15) -> no change
1815     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1816     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1817       break;
1818     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1819     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1820     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1821       return RHS;
1822     }
1823     break;
1824   case ICmpInst::ICMP_NE:
1825     switch (RHSCC) {
1826     default: llvm_unreachable("Unknown integer condition code!");
1827     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1828     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1829     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1830       return LHS;
1831     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1832     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1833     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1834       return Builder->getTrue();
1835     }
1836   case ICmpInst::ICMP_ULT:
1837     switch (RHSCC) {
1838     default: llvm_unreachable("Unknown integer condition code!");
1839     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1840       break;
1841     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1842       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1843       // this can cause overflow.
1844       if (RHSCst->isMaxValue(false))
1845         return LHS;
1846       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1847     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1848       break;
1849     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1850     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1851       return RHS;
1852     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1853       break;
1854     }
1855     break;
1856   case ICmpInst::ICMP_SLT:
1857     switch (RHSCC) {
1858     default: llvm_unreachable("Unknown integer condition code!");
1859     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1860       break;
1861     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1862       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1863       // this can cause overflow.
1864       if (RHSCst->isMaxValue(true))
1865         return LHS;
1866       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1867     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1868       break;
1869     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1870     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1871       return RHS;
1872     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1873       break;
1874     }
1875     break;
1876   case ICmpInst::ICMP_UGT:
1877     switch (RHSCC) {
1878     default: llvm_unreachable("Unknown integer condition code!");
1879     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1880     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1881       return LHS;
1882     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1883       break;
1884     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1885     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1886       return Builder->getTrue();
1887     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1888       break;
1889     }
1890     break;
1891   case ICmpInst::ICMP_SGT:
1892     switch (RHSCC) {
1893     default: llvm_unreachable("Unknown integer condition code!");
1894     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1895     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1896       return LHS;
1897     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1898       break;
1899     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1900     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1901       return Builder->getTrue();
1902     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1903       break;
1904     }
1905     break;
1906   }
1907   return nullptr;
1908 }
1909
1910 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1911 /// instcombine, this returns a Value which should already be inserted into the
1912 /// function.
1913 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1914   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1915       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1916       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1917     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1918       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1919         // If either of the constants are nans, then the whole thing returns
1920         // true.
1921         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1922           return Builder->getTrue();
1923
1924         // Otherwise, no need to compare the two constants, compare the
1925         // rest.
1926         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1927       }
1928
1929     // Handle vector zeros.  This occurs because the canonical form of
1930     // "fcmp uno x,x" is "fcmp uno x, 0".
1931     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1932         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1933       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1934
1935     return nullptr;
1936   }
1937
1938   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1939   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1940   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1941
1942   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1943     // Swap RHS operands to match LHS.
1944     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1945     std::swap(Op1LHS, Op1RHS);
1946   }
1947   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1948     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1949     if (Op0CC == Op1CC)
1950       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1951     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1952       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1953     if (Op0CC == FCmpInst::FCMP_FALSE)
1954       return RHS;
1955     if (Op1CC == FCmpInst::FCMP_FALSE)
1956       return LHS;
1957     bool Op0Ordered;
1958     bool Op1Ordered;
1959     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1960     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1961     if (Op0Ordered == Op1Ordered) {
1962       // If both are ordered or unordered, return a new fcmp with
1963       // or'ed predicates.
1964       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1965     }
1966   }
1967   return nullptr;
1968 }
1969
1970 /// FoldOrWithConstants - This helper function folds:
1971 ///
1972 ///     ((A | B) & C1) | (B & C2)
1973 ///
1974 /// into:
1975 ///
1976 ///     (A & C1) | B
1977 ///
1978 /// when the XOR of the two constants is "all ones" (-1).
1979 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1980                                                Value *A, Value *B, Value *C) {
1981   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1982   if (!CI1) return nullptr;
1983
1984   Value *V1 = nullptr;
1985   ConstantInt *CI2 = nullptr;
1986   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
1987
1988   APInt Xor = CI1->getValue() ^ CI2->getValue();
1989   if (!Xor.isAllOnesValue()) return nullptr;
1990
1991   if (V1 == A || V1 == B) {
1992     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1993     return BinaryOperator::CreateOr(NewOp, V1);
1994   }
1995
1996   return nullptr;
1997 }
1998
1999 /// \brief This helper function folds:
2000 ///
2001 ///     ((A | B) & C1) ^ (B & C2)
2002 ///
2003 /// into:
2004 ///
2005 ///     (A & C1) ^ B
2006 ///
2007 /// when the XOR of the two constants is "all ones" (-1).
2008 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2009                                                 Value *A, Value *B, Value *C) {
2010   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2011   if (!CI1)
2012     return nullptr;
2013
2014   Value *V1 = nullptr;
2015   ConstantInt *CI2 = nullptr;
2016   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2017     return nullptr;
2018
2019   APInt Xor = CI1->getValue() ^ CI2->getValue();
2020   if (!Xor.isAllOnesValue())
2021     return nullptr;
2022
2023   if (V1 == A || V1 == B) {
2024     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2025     return BinaryOperator::CreateXor(NewOp, V1);
2026   }
2027
2028   return nullptr;
2029 }
2030
2031 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2032   bool Changed = SimplifyAssociativeOrCommutative(I);
2033   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2034
2035   if (Value *V = SimplifyVectorOp(I))
2036     return ReplaceInstUsesWith(I, V);
2037
2038   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AT))
2039     return ReplaceInstUsesWith(I, V);
2040
2041   // (A&B)|(A&C) -> A&(B|C) etc
2042   if (Value *V = SimplifyUsingDistributiveLaws(I))
2043     return ReplaceInstUsesWith(I, V);
2044
2045   // See if we can simplify any instructions used by the instruction whose sole
2046   // purpose is to compute bits we don't care about.
2047   if (SimplifyDemandedInstructionBits(I))
2048     return &I;
2049
2050   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2051     ConstantInt *C1 = nullptr; Value *X = nullptr;
2052     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2053     // iff (C1 & C2) == 0.
2054     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
2055         (RHS->getValue() & C1->getValue()) != 0 &&
2056         Op0->hasOneUse()) {
2057       Value *Or = Builder->CreateOr(X, RHS);
2058       Or->takeName(Op0);
2059       return BinaryOperator::CreateAnd(Or,
2060                              Builder->getInt(RHS->getValue() | C1->getValue()));
2061     }
2062
2063     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2064     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2065         Op0->hasOneUse()) {
2066       Value *Or = Builder->CreateOr(X, RHS);
2067       Or->takeName(Op0);
2068       return BinaryOperator::CreateXor(Or,
2069                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
2070     }
2071
2072     // Try to fold constant and into select arguments.
2073     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2074       if (Instruction *R = FoldOpIntoSelect(I, SI))
2075         return R;
2076
2077     if (isa<PHINode>(Op0))
2078       if (Instruction *NV = FoldOpIntoPhi(I))
2079         return NV;
2080   }
2081
2082   Value *A = nullptr, *B = nullptr;
2083   ConstantInt *C1 = nullptr, *C2 = nullptr;
2084
2085   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
2086   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
2087   if (match(Op0, m_Or(m_Value(), m_Value())) ||
2088       match(Op1, m_Or(m_Value(), m_Value())) ||
2089       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2090        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
2091     if (Instruction *BSwap = MatchBSwap(I))
2092       return BSwap;
2093   }
2094
2095   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2096   if (Op0->hasOneUse() &&
2097       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2098       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
2099     Value *NOr = Builder->CreateOr(A, Op1);
2100     NOr->takeName(Op0);
2101     return BinaryOperator::CreateXor(NOr, C1);
2102   }
2103
2104   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2105   if (Op1->hasOneUse() &&
2106       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2107       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
2108     Value *NOr = Builder->CreateOr(A, Op0);
2109     NOr->takeName(Op0);
2110     return BinaryOperator::CreateXor(NOr, C1);
2111   }
2112
2113   // ((~A & B) | A) -> (A | B)
2114   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2115       match(Op1, m_Specific(A)))
2116     return BinaryOperator::CreateOr(A, B);
2117
2118   // ((A & B) | ~A) -> (~A | B)
2119   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2120       match(Op1, m_Not(m_Specific(A))))
2121     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2122
2123   // (A & (~B)) | (A ^ B) -> (A ^ B)
2124   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2125       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2126     return BinaryOperator::CreateXor(A, B);
2127
2128   // (A ^ B) | ( A & (~B)) -> (A ^ B)
2129   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2130       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2131     return BinaryOperator::CreateXor(A, B);
2132
2133   // (A & C)|(B & D)
2134   Value *C = nullptr, *D = nullptr;
2135   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2136       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2137     Value *V1 = nullptr, *V2 = nullptr;
2138     C1 = dyn_cast<ConstantInt>(C);
2139     C2 = dyn_cast<ConstantInt>(D);
2140     if (C1 && C2) {  // (A & C1)|(B & C2)
2141       if ((C1->getValue() & C2->getValue()) == 0) {
2142         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2143         // iff (C1&C2) == 0 and (N&~C1) == 0
2144         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2145             ((V1 == B &&
2146               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2147              (V2 == B &&
2148               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2149           return BinaryOperator::CreateAnd(A,
2150                                 Builder->getInt(C1->getValue()|C2->getValue()));
2151         // Or commutes, try both ways.
2152         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2153             ((V1 == A &&
2154               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2155              (V2 == A &&
2156               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2157           return BinaryOperator::CreateAnd(B,
2158                                 Builder->getInt(C1->getValue()|C2->getValue()));
2159
2160         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2161         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2162         ConstantInt *C3 = nullptr, *C4 = nullptr;
2163         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2164             (C3->getValue() & ~C1->getValue()) == 0 &&
2165             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2166             (C4->getValue() & ~C2->getValue()) == 0) {
2167           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2168           return BinaryOperator::CreateAnd(V2,
2169                                 Builder->getInt(C1->getValue()|C2->getValue()));
2170         }
2171       }
2172     }
2173
2174     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
2175     // Don't do this for vector select idioms, the code generator doesn't handle
2176     // them well yet.
2177     if (!I.getType()->isVectorTy()) {
2178       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2179         return Match;
2180       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2181         return Match;
2182       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2183         return Match;
2184       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2185         return Match;
2186     }
2187
2188     // ((A&~B)|(~A&B)) -> A^B
2189     if ((match(C, m_Not(m_Specific(D))) &&
2190          match(B, m_Not(m_Specific(A)))))
2191       return BinaryOperator::CreateXor(A, D);
2192     // ((~B&A)|(~A&B)) -> A^B
2193     if ((match(A, m_Not(m_Specific(D))) &&
2194          match(B, m_Not(m_Specific(C)))))
2195       return BinaryOperator::CreateXor(C, D);
2196     // ((A&~B)|(B&~A)) -> A^B
2197     if ((match(C, m_Not(m_Specific(B))) &&
2198          match(D, m_Not(m_Specific(A)))))
2199       return BinaryOperator::CreateXor(A, B);
2200     // ((~B&A)|(B&~A)) -> A^B
2201     if ((match(A, m_Not(m_Specific(B))) &&
2202          match(D, m_Not(m_Specific(C)))))
2203       return BinaryOperator::CreateXor(C, B);
2204
2205     // ((A|B)&1)|(B&-2) -> (A&1) | B
2206     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2207         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2208       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2209       if (Ret) return Ret;
2210     }
2211     // (B&-2)|((A|B)&1) -> (A&1) | B
2212     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2213         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2214       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2215       if (Ret) return Ret;
2216     }
2217     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2218     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2219         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2220       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2221       if (Ret) return Ret;
2222     }
2223     // (B&-2)|((A^B)&1) -> (A&1) ^ B
2224     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2225         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2226       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2227       if (Ret) return Ret;
2228     }
2229   }
2230
2231   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2232   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2233     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2234       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2235         return BinaryOperator::CreateOr(Op0, C);
2236
2237   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2238   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2239     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2240       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2241         return BinaryOperator::CreateOr(Op1, C);
2242
2243   // ((B | C) & A) | B -> B | (A & C)
2244   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2245     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2246
2247   // (~A | ~B) == (~(A & B)) - De Morgan's Law
2248   if (Value *Op0NotVal = dyn_castNotVal(Op0))
2249     if (Value *Op1NotVal = dyn_castNotVal(Op1))
2250       if (Op0->hasOneUse() && Op1->hasOneUse()) {
2251         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2252                                         I.getName()+".demorgan");
2253         return BinaryOperator::CreateNot(And);
2254       }
2255
2256   // Canonicalize xor to the RHS.
2257   bool SwappedForXor = false;
2258   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2259     std::swap(Op0, Op1);
2260     SwappedForXor = true;
2261   }
2262
2263   // A | ( A ^ B) -> A |  B
2264   // A | (~A ^ B) -> A | ~B
2265   // (A & B) | (A ^ B)
2266   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2267     if (Op0 == A || Op0 == B)
2268       return BinaryOperator::CreateOr(A, B);
2269
2270     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2271         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2272       return BinaryOperator::CreateOr(A, B);
2273
2274     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2275       Value *Not = Builder->CreateNot(B, B->getName()+".not");
2276       return BinaryOperator::CreateOr(Not, Op0);
2277     }
2278     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2279       Value *Not = Builder->CreateNot(A, A->getName()+".not");
2280       return BinaryOperator::CreateOr(Not, Op0);
2281     }
2282   }
2283
2284   // A | ~(A | B) -> A | ~B
2285   // A | ~(A ^ B) -> A | ~B
2286   if (match(Op1, m_Not(m_Value(A))))
2287     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2288       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2289           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2290                                B->getOpcode() == Instruction::Xor)) {
2291         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2292                                                  B->getOperand(0);
2293         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2294         return BinaryOperator::CreateOr(Not, Op0);
2295       }
2296
2297   // (A & B) | ((~A) ^ B) -> (~A ^ B)
2298   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2299       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2300     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2301
2302   // ((~A) ^ B) | (A & B) -> (~A ^ B)
2303   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2304       match(Op1, m_And(m_Specific(A), m_Specific(B))))
2305     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2306
2307   if (SwappedForXor)
2308     std::swap(Op0, Op1);
2309
2310   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2311     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2312       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2313         return ReplaceInstUsesWith(I, Res);
2314
2315   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
2316   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2317     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2318       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2319         return ReplaceInstUsesWith(I, Res);
2320
2321   // fold (or (cast A), (cast B)) -> (cast (or A, B))
2322   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2323     CastInst *Op1C = dyn_cast<CastInst>(Op1);
2324     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2325       Type *SrcTy = Op0C->getOperand(0)->getType();
2326       if (SrcTy == Op1C->getOperand(0)->getType() &&
2327           SrcTy->isIntOrIntVectorTy()) {
2328         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2329
2330         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2331             // Only do this if the casts both really cause code to be
2332             // generated.
2333             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2334             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2335           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2336           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2337         }
2338
2339         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2340         // cast is otherwise not optimizable.  This happens for vector sexts.
2341         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2342           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2343             if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2344               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2345
2346         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2347         // cast is otherwise not optimizable.  This happens for vector sexts.
2348         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2349           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2350             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2351               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2352       }
2353     }
2354   }
2355
2356   // or(sext(A), B) -> A ? -1 : B where A is an i1
2357   // or(A, sext(B)) -> B ? -1 : A where B is an i1
2358   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2359     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2360   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2361     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2362
2363   // Note: If we've gotten to the point of visiting the outer OR, then the
2364   // inner one couldn't be simplified.  If it was a constant, then it won't
2365   // be simplified by a later pass either, so we try swapping the inner/outer
2366   // ORs in the hopes that we'll be able to simplify it this way.
2367   // (X|C) | V --> (X|V) | C
2368   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2369       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2370     Value *Inner = Builder->CreateOr(A, Op1);
2371     Inner->takeName(Op0);
2372     return BinaryOperator::CreateOr(Inner, C1);
2373   }
2374
2375   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2376   // Since this OR statement hasn't been optimized further yet, we hope
2377   // that this transformation will allow the new ORs to be optimized.
2378   {
2379     Value *X = nullptr, *Y = nullptr;
2380     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2381         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2382         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2383       Value *orTrue = Builder->CreateOr(A, C);
2384       Value *orFalse = Builder->CreateOr(B, D);
2385       return SelectInst::Create(X, orTrue, orFalse);
2386     }
2387   }
2388
2389   return Changed ? &I : nullptr;
2390 }
2391
2392 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2393   bool Changed = SimplifyAssociativeOrCommutative(I);
2394   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2395
2396   if (Value *V = SimplifyVectorOp(I))
2397     return ReplaceInstUsesWith(I, V);
2398
2399   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AT))
2400     return ReplaceInstUsesWith(I, V);
2401
2402   // (A&B)^(A&C) -> A&(B^C) etc
2403   if (Value *V = SimplifyUsingDistributiveLaws(I))
2404     return ReplaceInstUsesWith(I, V);
2405
2406   // See if we can simplify any instructions used by the instruction whose sole
2407   // purpose is to compute bits we don't care about.
2408   if (SimplifyDemandedInstructionBits(I))
2409     return &I;
2410
2411   // Is this a ~ operation?
2412   if (Value *NotOp = dyn_castNotVal(&I)) {
2413     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2414       if (Op0I->getOpcode() == Instruction::And ||
2415           Op0I->getOpcode() == Instruction::Or) {
2416         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2417         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2418         if (dyn_castNotVal(Op0I->getOperand(1)))
2419           Op0I->swapOperands();
2420         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2421           Value *NotY =
2422             Builder->CreateNot(Op0I->getOperand(1),
2423                                Op0I->getOperand(1)->getName()+".not");
2424           if (Op0I->getOpcode() == Instruction::And)
2425             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2426           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2427         }
2428
2429         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2430         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2431         if (isFreeToInvert(Op0I->getOperand(0)) &&
2432             isFreeToInvert(Op0I->getOperand(1))) {
2433           Value *NotX =
2434             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2435           Value *NotY =
2436             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2437           if (Op0I->getOpcode() == Instruction::And)
2438             return BinaryOperator::CreateOr(NotX, NotY);
2439           return BinaryOperator::CreateAnd(NotX, NotY);
2440         }
2441
2442       } else if (Op0I->getOpcode() == Instruction::AShr) {
2443         // ~(~X >>s Y) --> (X >>s Y)
2444         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2445           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2446       }
2447     }
2448   }
2449
2450
2451   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2452     if (RHS->isOne() && Op0->hasOneUse())
2453       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2454       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2455         return CmpInst::Create(CI->getOpcode(),
2456                                CI->getInversePredicate(),
2457                                CI->getOperand(0), CI->getOperand(1));
2458
2459     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2460     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2461       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2462         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2463           Instruction::CastOps Opcode = Op0C->getOpcode();
2464           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2465               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2466                                             Op0C->getDestTy()))) {
2467             CI->setPredicate(CI->getInversePredicate());
2468             return CastInst::Create(Opcode, CI, Op0C->getType());
2469           }
2470         }
2471       }
2472     }
2473
2474     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2475       // ~(c-X) == X-c-1 == X+(-c-1)
2476       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2477         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2478           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2479           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2480                                       ConstantInt::get(I.getType(), 1));
2481           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2482         }
2483
2484       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2485         if (Op0I->getOpcode() == Instruction::Add) {
2486           // ~(X-c) --> (-c-1)-X
2487           if (RHS->isAllOnesValue()) {
2488             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2489             return BinaryOperator::CreateSub(
2490                            ConstantExpr::getSub(NegOp0CI,
2491                                       ConstantInt::get(I.getType(), 1)),
2492                                       Op0I->getOperand(0));
2493           } else if (RHS->getValue().isSignBit()) {
2494             // (X + C) ^ signbit -> (X + C + signbit)
2495             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2496             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2497
2498           }
2499         } else if (Op0I->getOpcode() == Instruction::Or) {
2500           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2501           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2502                                 0, &I)) {
2503             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2504             // Anything in both C1 and C2 is known to be zero, remove it from
2505             // NewRHS.
2506             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2507             NewRHS = ConstantExpr::getAnd(NewRHS,
2508                                        ConstantExpr::getNot(CommonBits));
2509             Worklist.Add(Op0I);
2510             I.setOperand(0, Op0I->getOperand(0));
2511             I.setOperand(1, NewRHS);
2512             return &I;
2513           }
2514         } else if (Op0I->getOpcode() == Instruction::LShr) {
2515           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2516           // E1 = "X ^ C1"
2517           BinaryOperator *E1;
2518           ConstantInt *C1;
2519           if (Op0I->hasOneUse() &&
2520               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2521               E1->getOpcode() == Instruction::Xor &&
2522               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2523             // fold (C1 >> C2) ^ C3
2524             ConstantInt *C2 = Op0CI, *C3 = RHS;
2525             APInt FoldConst = C1->getValue().lshr(C2->getValue());
2526             FoldConst ^= C3->getValue();
2527             // Prepare the two operands.
2528             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2529             Opnd0->takeName(Op0I);
2530             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2531             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2532
2533             return BinaryOperator::CreateXor(Opnd0, FoldVal);
2534           }
2535         }
2536       }
2537     }
2538
2539     // Try to fold constant and into select arguments.
2540     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2541       if (Instruction *R = FoldOpIntoSelect(I, SI))
2542         return R;
2543     if (isa<PHINode>(Op0))
2544       if (Instruction *NV = FoldOpIntoPhi(I))
2545         return NV;
2546   }
2547
2548   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2549   if (Op1I) {
2550     Value *A, *B;
2551     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2552       if (A == Op0) {              // B^(B|A) == (A|B)^B
2553         Op1I->swapOperands();
2554         I.swapOperands();
2555         std::swap(Op0, Op1);
2556       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2557         I.swapOperands();     // Simplified below.
2558         std::swap(Op0, Op1);
2559       }
2560     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2561                Op1I->hasOneUse()){
2562       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2563         Op1I->swapOperands();
2564         std::swap(A, B);
2565       }
2566       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2567         I.swapOperands();     // Simplified below.
2568         std::swap(Op0, Op1);
2569       }
2570     }
2571   }
2572
2573   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2574   if (Op0I) {
2575     Value *A, *B;
2576     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2577         Op0I->hasOneUse()) {
2578       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2579         std::swap(A, B);
2580       if (B == Op1)                                  // (A|B)^B == A & ~B
2581         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2582     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2583                Op0I->hasOneUse()){
2584       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2585         std::swap(A, B);
2586       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2587           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2588         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2589       }
2590     }
2591   }
2592
2593   if (Op0I && Op1I) {
2594     Value *A, *B, *C, *D;
2595     // (A & B)^(A | B) -> A ^ B
2596     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2597         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2598       if ((A == C && B == D) || (A == D && B == C))
2599         return BinaryOperator::CreateXor(A, B);
2600     }
2601     // (A | B)^(A & B) -> A ^ B
2602     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2603         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2604       if ((A == C && B == D) || (A == D && B == C))
2605         return BinaryOperator::CreateXor(A, B);
2606     }
2607     // (A | ~B) ^ (~A | B) -> A ^ B
2608     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2609         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2610       return BinaryOperator::CreateXor(A, B);
2611     }
2612     // (~A | B) ^ (A | ~B) -> A ^ B
2613     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2614         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2615       return BinaryOperator::CreateXor(A, B);
2616     }
2617     // (A & ~B) ^ (~A & B) -> A ^ B
2618     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2619         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2620       return BinaryOperator::CreateXor(A, B);
2621     }
2622     // (~A & B) ^ (A & ~B) -> A ^ B
2623     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2624         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2625       return BinaryOperator::CreateXor(A, B);
2626     }
2627     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2628     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2629         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2630       if (D == A)
2631         return BinaryOperator::CreateXor(
2632             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2633       if (D == B)
2634         return BinaryOperator::CreateXor(
2635             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2636     }
2637     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2638     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2639         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2640       if (D == A)
2641         return BinaryOperator::CreateXor(
2642             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2643       if (D == B)
2644         return BinaryOperator::CreateXor(
2645             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2646     }
2647     // (A & B) ^ (A ^ B) -> (A | B)
2648     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2649         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2650       return BinaryOperator::CreateOr(A, B);
2651     // (A ^ B) ^ (A & B) -> (A | B)
2652     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2653         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2654       return BinaryOperator::CreateOr(A, B);
2655   }
2656
2657   Value *A = nullptr, *B = nullptr;
2658   // (A & ~B) ^ (~A) -> ~(A & B)
2659   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2660       match(Op1, m_Not(m_Specific(A))))
2661     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2662
2663   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2664   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2665     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2666       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2667         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2668             LHS->getOperand(1) == RHS->getOperand(0))
2669           LHS->swapOperands();
2670         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2671             LHS->getOperand(1) == RHS->getOperand(1)) {
2672           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2673           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2674           bool isSigned = LHS->isSigned() || RHS->isSigned();
2675           return ReplaceInstUsesWith(I,
2676                                getNewICmpValue(isSigned, Code, Op0, Op1,
2677                                                Builder));
2678         }
2679       }
2680
2681   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2682   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2683     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2684       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2685         Type *SrcTy = Op0C->getOperand(0)->getType();
2686         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2687             // Only do this if the casts both really cause code to be generated.
2688             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2689                                I.getType()) &&
2690             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2691                                I.getType())) {
2692           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2693                                             Op1C->getOperand(0), I.getName());
2694           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2695         }
2696       }
2697   }
2698
2699   return Changed ? &I : nullptr;
2700 }