1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitAnd, visitOr, and visitXor functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/CmpInstAnalysis.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/InstCombine/InstCombiner.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// This is the complement of getICmpCode, which turns an opcode and two
28 /// operands into either a constant true or false, or a brand new ICmp
29 /// instruction. The sign is passed in to determine which kind of predicate to
30 /// use in the new icmp instruction.
31 static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
32                               InstCombiner::BuilderTy &Builder) {
33   ICmpInst::Predicate NewPred;
34   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
35     return TorF;
36   return Builder.CreateICmp(NewPred, LHS, RHS);
37 }
38 
39 /// This is the complement of getFCmpCode, which turns an opcode and two
40 /// operands into either a FCmp instruction, or a true/false constant.
41 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
42                            InstCombiner::BuilderTy &Builder) {
43   FCmpInst::Predicate NewPred;
44   if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
45     return TorF;
46   return Builder.CreateFCmp(NewPred, LHS, RHS);
47 }
48 
49 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
50 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
51 /// \param I Binary operator to transform.
52 /// \return Pointer to node that must replace the original binary operator, or
53 ///         null pointer if no transformation was made.
54 static Value *SimplifyBSwap(BinaryOperator &I,
55                             InstCombiner::BuilderTy &Builder) {
56   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
57 
58   Value *OldLHS = I.getOperand(0);
59   Value *OldRHS = I.getOperand(1);
60 
61   Value *NewLHS;
62   if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
63     return nullptr;
64 
65   Value *NewRHS;
66   const APInt *C;
67 
68   if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
69     // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
70     if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
71       return nullptr;
72     // NewRHS initialized by the matcher.
73   } else if (match(OldRHS, m_APInt(C))) {
74     // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
75     if (!OldLHS->hasOneUse())
76       return nullptr;
77     NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
78   } else
79     return nullptr;
80 
81   Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
82   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
83                                           I.getType());
84   return Builder.CreateCall(F, BinOp);
85 }
86 
87 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
88 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
89 /// whether to treat V, Lo, and Hi as signed or not.
90 Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
91                                          const APInt &Hi, bool isSigned,
92                                          bool Inside) {
93   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
94          "Lo is not < Hi in range emission code!");
95 
96   Type *Ty = V->getType();
97 
98   // V >= Min && V <  Hi --> V <  Hi
99   // V <  Min || V >= Hi --> V >= Hi
100   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
101   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
102     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
103     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
104   }
105 
106   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
107   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
108   Value *VMinusLo =
109       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
110   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
111   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
112 }
113 
114 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
115 /// that can be simplified.
116 /// One of A and B is considered the mask. The other is the value. This is
117 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
118 /// only "Mask", then both A and B can be considered masks. If A is the mask,
119 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
120 /// If both A and C are constants, this proof is also easy.
121 /// For the following explanations, we assume that A is the mask.
122 ///
123 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
124 /// bits of A are set in B.
125 ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
126 ///
127 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
128 /// bits of A are cleared in B.
129 ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
130 ///
131 /// "Mixed" declares that (A & B) == C and C might or might not contain any
132 /// number of one bits and zero bits.
133 ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
134 ///
135 /// "Not" means that in above descriptions "==" should be replaced by "!=".
136 ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
137 ///
138 /// If the mask A contains a single bit, then the following is equivalent:
139 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
140 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
141 enum MaskedICmpType {
142   AMask_AllOnes           =     1,
143   AMask_NotAllOnes        =     2,
144   BMask_AllOnes           =     4,
145   BMask_NotAllOnes        =     8,
146   Mask_AllZeros           =    16,
147   Mask_NotAllZeros        =    32,
148   AMask_Mixed             =    64,
149   AMask_NotMixed          =   128,
150   BMask_Mixed             =   256,
151   BMask_NotMixed          =   512
152 };
153 
154 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
155 /// satisfies.
156 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
157                                   ICmpInst::Predicate Pred) {
158   const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
159   match(A, m_APInt(ConstA));
160   match(B, m_APInt(ConstB));
161   match(C, m_APInt(ConstC));
162   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
163   bool IsAPow2 = ConstA && ConstA->isPowerOf2();
164   bool IsBPow2 = ConstB && ConstB->isPowerOf2();
165   unsigned MaskVal = 0;
166   if (ConstC && ConstC->isZero()) {
167     // if C is zero, then both A and B qualify as mask
168     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
169                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
170     if (IsAPow2)
171       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
172                        : (AMask_AllOnes | AMask_Mixed));
173     if (IsBPow2)
174       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
175                        : (BMask_AllOnes | BMask_Mixed));
176     return MaskVal;
177   }
178 
179   if (A == C) {
180     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
181                      : (AMask_NotAllOnes | AMask_NotMixed));
182     if (IsAPow2)
183       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
184                        : (Mask_AllZeros | AMask_Mixed));
185   } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
186     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
187   }
188 
189   if (B == C) {
190     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
191                      : (BMask_NotAllOnes | BMask_NotMixed));
192     if (IsBPow2)
193       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
194                        : (Mask_AllZeros | BMask_Mixed));
195   } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
196     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
197   }
198 
199   return MaskVal;
200 }
201 
202 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
203 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
204 /// is adjacent to the corresponding normal flag (recording ==), this just
205 /// involves swapping those bits over.
206 static unsigned conjugateICmpMask(unsigned Mask) {
207   unsigned NewMask;
208   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
209                      AMask_Mixed | BMask_Mixed))
210             << 1;
211 
212   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
213                       AMask_NotMixed | BMask_NotMixed))
214              >> 1;
215 
216   return NewMask;
217 }
218 
219 // Adapts the external decomposeBitTestICmp for local use.
220 static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
221                                  Value *&X, Value *&Y, Value *&Z) {
222   APInt Mask;
223   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
224     return false;
225 
226   Y = ConstantInt::get(X->getType(), Mask);
227   Z = ConstantInt::get(X->getType(), 0);
228   return true;
229 }
230 
231 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
232 /// Return the pattern classes (from MaskedICmpType) for the left hand side and
233 /// the right hand side as a pair.
234 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
235 /// and PredR are their predicates, respectively.
236 static
237 Optional<std::pair<unsigned, unsigned>>
238 getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
239                          Value *&D, Value *&E, ICmpInst *LHS,
240                          ICmpInst *RHS,
241                          ICmpInst::Predicate &PredL,
242                          ICmpInst::Predicate &PredR) {
243   // Don't allow pointers. Splat vectors are fine.
244   if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
245       !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
246     return None;
247 
248   // Here comes the tricky part:
249   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
250   // and L11 & L12 == L21 & L22. The same goes for RHS.
251   // Now we must find those components L** and R**, that are equal, so
252   // that we can extract the parameters A, B, C, D, and E for the canonical
253   // above.
254   Value *L1 = LHS->getOperand(0);
255   Value *L2 = LHS->getOperand(1);
256   Value *L11, *L12, *L21, *L22;
257   // Check whether the icmp can be decomposed into a bit test.
258   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
259     L21 = L22 = L1 = nullptr;
260   } else {
261     // Look for ANDs in the LHS icmp.
262     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
263       // Any icmp can be viewed as being trivially masked; if it allows us to
264       // remove one, it's worth it.
265       L11 = L1;
266       L12 = Constant::getAllOnesValue(L1->getType());
267     }
268 
269     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
270       L21 = L2;
271       L22 = Constant::getAllOnesValue(L2->getType());
272     }
273   }
274 
275   // Bail if LHS was a icmp that can't be decomposed into an equality.
276   if (!ICmpInst::isEquality(PredL))
277     return None;
278 
279   Value *R1 = RHS->getOperand(0);
280   Value *R2 = RHS->getOperand(1);
281   Value *R11, *R12;
282   bool Ok = false;
283   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
284     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
285       A = R11;
286       D = R12;
287     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
288       A = R12;
289       D = R11;
290     } else {
291       return None;
292     }
293     E = R2;
294     R1 = nullptr;
295     Ok = true;
296   } else {
297     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
298       // As before, model no mask as a trivial mask if it'll let us do an
299       // optimization.
300       R11 = R1;
301       R12 = Constant::getAllOnesValue(R1->getType());
302     }
303 
304     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
305       A = R11;
306       D = R12;
307       E = R2;
308       Ok = true;
309     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
310       A = R12;
311       D = R11;
312       E = R2;
313       Ok = true;
314     }
315   }
316 
317   // Bail if RHS was a icmp that can't be decomposed into an equality.
318   if (!ICmpInst::isEquality(PredR))
319     return None;
320 
321   // Look for ANDs on the right side of the RHS icmp.
322   if (!Ok) {
323     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
324       R11 = R2;
325       R12 = Constant::getAllOnesValue(R2->getType());
326     }
327 
328     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
329       A = R11;
330       D = R12;
331       E = R1;
332       Ok = true;
333     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
334       A = R12;
335       D = R11;
336       E = R1;
337       Ok = true;
338     } else {
339       return None;
340     }
341 
342     assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
343   }
344 
345   if (L11 == A) {
346     B = L12;
347     C = L2;
348   } else if (L12 == A) {
349     B = L11;
350     C = L2;
351   } else if (L21 == A) {
352     B = L22;
353     C = L1;
354   } else if (L22 == A) {
355     B = L21;
356     C = L1;
357   }
358 
359   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
360   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
361   return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
362 }
363 
364 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
365 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
366 /// and the right hand side is of type BMask_Mixed. For example,
367 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
368 static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
369     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
370     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
371     InstCombiner::BuilderTy &Builder) {
372   // We are given the canonical form:
373   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
374   // where D & E == E.
375   //
376   // If IsAnd is false, we get it in negated form:
377   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
378   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
379   //
380   // We currently handle the case of B, C, D, E are constant.
381   //
382   ConstantInt *BCst, *CCst, *DCst, *ECst;
383   if (!match(B, m_ConstantInt(BCst)) || !match(C, m_ConstantInt(CCst)) ||
384       !match(D, m_ConstantInt(DCst)) || !match(E, m_ConstantInt(ECst)))
385     return nullptr;
386 
387   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
388 
389   // Update E to the canonical form when D is a power of two and RHS is
390   // canonicalized as,
391   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
392   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
393   if (PredR != NewCC)
394     ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
395 
396   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
397   // other folding rules and this pattern won't apply any more.
398   if (BCst->getValue() == 0 || DCst->getValue() == 0)
399     return nullptr;
400 
401   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
402   // deduce anything from it.
403   // For example,
404   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
405   if ((BCst->getValue() & DCst->getValue()) == 0)
406     return nullptr;
407 
408   // If the following two conditions are met:
409   //
410   // 1. mask B covers only a single bit that's not covered by mask D, that is,
411   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
412   // B and D has only one bit set) and,
413   //
414   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
415   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
416   //
417   // then that single bit in B must be one and thus the whole expression can be
418   // folded to
419   //   (A & (B | D)) == (B & (B ^ D)) | E.
420   //
421   // For example,
422   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
423   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
424   if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) &&
425       (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) {
426     APInt BorD = BCst->getValue() | DCst->getValue();
427     APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) |
428         ECst->getValue();
429     Value *NewMask = ConstantInt::get(BCst->getType(), BorD);
430     Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE);
431     Value *NewAnd = Builder.CreateAnd(A, NewMask);
432     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
433   }
434 
435   auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
436     return (C1->getValue() & C2->getValue()) == C1->getValue();
437   };
438   auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
439     return (C1->getValue() & C2->getValue()) == C2->getValue();
440   };
441 
442   // In the following, we consider only the cases where B is a superset of D, B
443   // is a subset of D, or B == D because otherwise there's at least one bit
444   // covered by B but not D, in which case we can't deduce much from it, so
445   // no folding (aside from the single must-be-one bit case right above.)
446   // For example,
447   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
448   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
449     return nullptr;
450 
451   // At this point, either B is a superset of D, B is a subset of D or B == D.
452 
453   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
454   // and the whole expression becomes false (or true if negated), otherwise, no
455   // folding.
456   // For example,
457   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
458   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
459   if (ECst->isZero()) {
460     if (IsSubSetOrEqual(BCst, DCst))
461       return ConstantInt::get(LHS->getType(), !IsAnd);
462     return nullptr;
463   }
464 
465   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
466   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
467   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
468   // RHS. For example,
469   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
470   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
471   if (IsSuperSetOrEqual(BCst, DCst))
472     return RHS;
473   // Otherwise, B is a subset of D. If B and E have a common bit set,
474   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
475   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
476   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
477   if ((BCst->getValue() & ECst->getValue()) != 0)
478     return RHS;
479   // Otherwise, LHS and RHS contradict and the whole expression becomes false
480   // (or true if negated.) For example,
481   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
482   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
483   return ConstantInt::get(LHS->getType(), !IsAnd);
484 }
485 
486 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
487 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
488 /// aren't of the common mask pattern type.
489 static Value *foldLogOpOfMaskedICmpsAsymmetric(
490     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
491     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
492     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
493   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
494          "Expected equality predicates for masked type of icmps.");
495   // Handle Mask_NotAllZeros-BMask_Mixed cases.
496   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
497   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
498   //    which gets swapped to
499   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
500   if (!IsAnd) {
501     LHSMask = conjugateICmpMask(LHSMask);
502     RHSMask = conjugateICmpMask(RHSMask);
503   }
504   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
505     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
506             LHS, RHS, IsAnd, A, B, C, D, E,
507             PredL, PredR, Builder)) {
508       return V;
509     }
510   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
511     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
512             RHS, LHS, IsAnd, A, D, E, B, C,
513             PredR, PredL, Builder)) {
514       return V;
515     }
516   }
517   return nullptr;
518 }
519 
520 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
521 /// into a single (icmp(A & X) ==/!= Y).
522 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
523                                      InstCombiner::BuilderTy &Builder) {
524   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
525   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
526   Optional<std::pair<unsigned, unsigned>> MaskPair =
527       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
528   if (!MaskPair)
529     return nullptr;
530   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
531          "Expected equality predicates for masked type of icmps.");
532   unsigned LHSMask = MaskPair->first;
533   unsigned RHSMask = MaskPair->second;
534   unsigned Mask = LHSMask & RHSMask;
535   if (Mask == 0) {
536     // Even if the two sides don't share a common pattern, check if folding can
537     // still happen.
538     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
539             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
540             Builder))
541       return V;
542     return nullptr;
543   }
544 
545   // In full generality:
546   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
547   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
548   //
549   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
550   // equivalent to (icmp (A & X) !Op Y).
551   //
552   // Therefore, we can pretend for the rest of this function that we're dealing
553   // with the conjunction, provided we flip the sense of any comparisons (both
554   // input and output).
555 
556   // In most cases we're going to produce an EQ for the "&&" case.
557   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
558   if (!IsAnd) {
559     // Convert the masking analysis into its equivalent with negated
560     // comparisons.
561     Mask = conjugateICmpMask(Mask);
562   }
563 
564   if (Mask & Mask_AllZeros) {
565     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
566     // -> (icmp eq (A & (B|D)), 0)
567     Value *NewOr = Builder.CreateOr(B, D);
568     Value *NewAnd = Builder.CreateAnd(A, NewOr);
569     // We can't use C as zero because we might actually handle
570     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
571     // with B and D, having a single bit set.
572     Value *Zero = Constant::getNullValue(A->getType());
573     return Builder.CreateICmp(NewCC, NewAnd, Zero);
574   }
575   if (Mask & BMask_AllOnes) {
576     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
577     // -> (icmp eq (A & (B|D)), (B|D))
578     Value *NewOr = Builder.CreateOr(B, D);
579     Value *NewAnd = Builder.CreateAnd(A, NewOr);
580     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
581   }
582   if (Mask & AMask_AllOnes) {
583     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
584     // -> (icmp eq (A & (B&D)), A)
585     Value *NewAnd1 = Builder.CreateAnd(B, D);
586     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
587     return Builder.CreateICmp(NewCC, NewAnd2, A);
588   }
589 
590   // Remaining cases assume at least that B and D are constant, and depend on
591   // their actual values. This isn't strictly necessary, just a "handle the
592   // easy cases for now" decision.
593   const APInt *ConstB, *ConstD;
594   if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
595     return nullptr;
596 
597   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
598     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
599     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
600     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
601     // Only valid if one of the masks is a superset of the other (check "B&D" is
602     // the same as either B or D).
603     APInt NewMask = *ConstB & *ConstD;
604     if (NewMask == *ConstB)
605       return LHS;
606     else if (NewMask == *ConstD)
607       return RHS;
608   }
609 
610   if (Mask & AMask_NotAllOnes) {
611     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
612     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
613     // Only valid if one of the masks is a superset of the other (check "B|D" is
614     // the same as either B or D).
615     APInt NewMask = *ConstB | *ConstD;
616     if (NewMask == *ConstB)
617       return LHS;
618     else if (NewMask == *ConstD)
619       return RHS;
620   }
621 
622   if (Mask & BMask_Mixed) {
623     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
624     // We already know that B & C == C && D & E == E.
625     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
626     // C and E, which are shared by both the mask B and the mask D, don't
627     // contradict, then we can transform to
628     // -> (icmp eq (A & (B|D)), (C|E))
629     // Currently, we only handle the case of B, C, D, and E being constant.
630     // We can't simply use C and E because we might actually handle
631     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
632     // with B and D, having a single bit set.
633     const APInt *OldConstC, *OldConstE;
634     if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
635       return nullptr;
636 
637     const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC;
638     const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE;
639 
640     // If there is a conflict, we should actually return a false for the
641     // whole construct.
642     if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
643       return ConstantInt::get(LHS->getType(), !IsAnd);
644 
645     Value *NewOr1 = Builder.CreateOr(B, D);
646     Value *NewAnd = Builder.CreateAnd(A, NewOr1);
647     Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE);
648     return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
649   }
650 
651   return nullptr;
652 }
653 
654 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
655 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
656 /// If \p Inverted is true then the check is for the inverted range, e.g.
657 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
658 Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
659                                             bool Inverted) {
660   // Check the lower range comparison, e.g. x >= 0
661   // InstCombine already ensured that if there is a constant it's on the RHS.
662   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
663   if (!RangeStart)
664     return nullptr;
665 
666   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
667                                Cmp0->getPredicate());
668 
669   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
670   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
671         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
672     return nullptr;
673 
674   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
675                                Cmp1->getPredicate());
676 
677   Value *Input = Cmp0->getOperand(0);
678   Value *RangeEnd;
679   if (Cmp1->getOperand(0) == Input) {
680     // For the upper range compare we have: icmp x, n
681     RangeEnd = Cmp1->getOperand(1);
682   } else if (Cmp1->getOperand(1) == Input) {
683     // For the upper range compare we have: icmp n, x
684     RangeEnd = Cmp1->getOperand(0);
685     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
686   } else {
687     return nullptr;
688   }
689 
690   // Check the upper range comparison, e.g. x < n
691   ICmpInst::Predicate NewPred;
692   switch (Pred1) {
693     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
694     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
695     default: return nullptr;
696   }
697 
698   // This simplification is only valid if the upper range is not negative.
699   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
700   if (!Known.isNonNegative())
701     return nullptr;
702 
703   if (Inverted)
704     NewPred = ICmpInst::getInversePredicate(NewPred);
705 
706   return Builder.CreateICmp(NewPred, Input, RangeEnd);
707 }
708 
709 static Value *
710 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
711                                      bool JoinedByAnd,
712                                      InstCombiner::BuilderTy &Builder) {
713   Value *X = LHS->getOperand(0);
714   if (X != RHS->getOperand(0))
715     return nullptr;
716 
717   const APInt *C1, *C2;
718   if (!match(LHS->getOperand(1), m_APInt(C1)) ||
719       !match(RHS->getOperand(1), m_APInt(C2)))
720     return nullptr;
721 
722   // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
723   ICmpInst::Predicate Pred = LHS->getPredicate();
724   if (Pred !=  RHS->getPredicate())
725     return nullptr;
726   if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
727     return nullptr;
728   if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
729     return nullptr;
730 
731   // The larger unsigned constant goes on the right.
732   if (C1->ugt(*C2))
733     std::swap(C1, C2);
734 
735   APInt Xor = *C1 ^ *C2;
736   if (Xor.isPowerOf2()) {
737     // If LHSC and RHSC differ by only one bit, then set that bit in X and
738     // compare against the larger constant:
739     // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
740     // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
741     // We choose an 'or' with a Pow2 constant rather than the inverse mask with
742     // 'and' because that may lead to smaller codegen from a smaller constant.
743     Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
744     return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
745   }
746 
747   return nullptr;
748 }
749 
750 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
751 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
752 Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
753                                                        ICmpInst *RHS,
754                                                        Instruction *CxtI,
755                                                        bool IsAnd,
756                                                        bool IsLogical) {
757   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
758   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
759     return nullptr;
760 
761   if (!match(LHS->getOperand(1), m_Zero()) ||
762       !match(RHS->getOperand(1), m_Zero()))
763     return nullptr;
764 
765   Value *L1, *L2, *R1, *R2;
766   if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
767       match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
768     if (L1 == R2 || L2 == R2)
769       std::swap(R1, R2);
770     if (L2 == R1)
771       std::swap(L1, L2);
772 
773     if (L1 == R1 &&
774         isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
775         isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
776       // If this is a logical and/or, then we must prevent propagation of a
777       // poison value from the RHS by inserting freeze.
778       if (IsLogical)
779         R2 = Builder.CreateFreeze(R2);
780       Value *Mask = Builder.CreateOr(L2, R2);
781       Value *Masked = Builder.CreateAnd(L1, Mask);
782       auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
783       return Builder.CreateICmp(NewPred, Masked, Mask);
784     }
785   }
786 
787   return nullptr;
788 }
789 
790 /// General pattern:
791 ///   X & Y
792 ///
793 /// Where Y is checking that all the high bits (covered by a mask 4294967168)
794 /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
795 /// Pattern can be one of:
796 ///   %t = add        i32 %arg,    128
797 ///   %r = icmp   ult i32 %t,      256
798 /// Or
799 ///   %t0 = shl       i32 %arg,    24
800 ///   %t1 = ashr      i32 %t0,     24
801 ///   %r  = icmp  eq  i32 %t1,     %arg
802 /// Or
803 ///   %t0 = trunc     i32 %arg  to i8
804 ///   %t1 = sext      i8  %t0   to i32
805 ///   %r  = icmp  eq  i32 %t1,     %arg
806 /// This pattern is a signed truncation check.
807 ///
808 /// And X is checking that some bit in that same mask is zero.
809 /// I.e. can be one of:
810 ///   %r = icmp sgt i32   %arg,    -1
811 /// Or
812 ///   %t = and      i32   %arg,    2147483648
813 ///   %r = icmp eq  i32   %t,      0
814 ///
815 /// Since we are checking that all the bits in that mask are the same,
816 /// and a particular bit is zero, what we are really checking is that all the
817 /// masked bits are zero.
818 /// So this should be transformed to:
819 ///   %r = icmp ult i32 %arg, 128
820 static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
821                                         Instruction &CxtI,
822                                         InstCombiner::BuilderTy &Builder) {
823   assert(CxtI.getOpcode() == Instruction::And);
824 
825   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
826   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
827                                             APInt &SignBitMask) -> bool {
828     CmpInst::Predicate Pred;
829     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
830     if (!(match(ICmp,
831                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
832           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
833       return false;
834     // Which bit is the new sign bit as per the 'signed truncation' pattern?
835     SignBitMask = *I01;
836     return true;
837   };
838 
839   // One icmp needs to be 'signed truncation check'.
840   // We need to match this first, else we will mismatch commutative cases.
841   Value *X1;
842   APInt HighestBit;
843   ICmpInst *OtherICmp;
844   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
845     OtherICmp = ICmp0;
846   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
847     OtherICmp = ICmp1;
848   else
849     return nullptr;
850 
851   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
852 
853   // Try to match/decompose into:  icmp eq (X & Mask), 0
854   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
855                            APInt &UnsetBitsMask) -> bool {
856     CmpInst::Predicate Pred = ICmp->getPredicate();
857     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
858     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
859                                    Pred, X, UnsetBitsMask,
860                                    /*LookThroughTrunc=*/false) &&
861         Pred == ICmpInst::ICMP_EQ)
862       return true;
863     // Is it  icmp eq (X & Mask), 0  already?
864     const APInt *Mask;
865     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
866         Pred == ICmpInst::ICMP_EQ) {
867       UnsetBitsMask = *Mask;
868       return true;
869     }
870     return false;
871   };
872 
873   // And the other icmp needs to be decomposable into a bit test.
874   Value *X0;
875   APInt UnsetBitsMask;
876   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
877     return nullptr;
878 
879   assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
880 
881   // Are they working on the same value?
882   Value *X;
883   if (X1 == X0) {
884     // Ok as is.
885     X = X1;
886   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
887     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
888     X = X1;
889   } else
890     return nullptr;
891 
892   // So which bits should be uniform as per the 'signed truncation check'?
893   // (all the bits starting with (i.e. including) HighestBit)
894   APInt SignBitsMask = ~(HighestBit - 1U);
895 
896   // UnsetBitsMask must have some common bits with SignBitsMask,
897   if (!UnsetBitsMask.intersects(SignBitsMask))
898     return nullptr;
899 
900   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
901   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
902     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
903     if (!OtherHighestBit.isPowerOf2())
904       return nullptr;
905     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
906   }
907   // Else, if it does not, then all is ok as-is.
908 
909   // %r = icmp ult %X, SignBit
910   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
911                                CxtI.getName() + ".simplified");
912 }
913 
914 /// Reduce a pair of compares that check if a value has exactly 1 bit set.
915 static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
916                              InstCombiner::BuilderTy &Builder) {
917   // Handle 'and' / 'or' commutation: make the equality check the first operand.
918   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
919     std::swap(Cmp0, Cmp1);
920   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
921     std::swap(Cmp0, Cmp1);
922 
923   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
924   CmpInst::Predicate Pred0, Pred1;
925   Value *X;
926   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
927       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
928                          m_SpecificInt(2))) &&
929       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
930     Value *CtPop = Cmp1->getOperand(0);
931     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
932   }
933   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
934   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
935       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
936                          m_SpecificInt(1))) &&
937       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
938     Value *CtPop = Cmp1->getOperand(0);
939     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
940   }
941   return nullptr;
942 }
943 
944 /// Commuted variants are assumed to be handled by calling this function again
945 /// with the parameters swapped.
946 static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
947                                          ICmpInst *UnsignedICmp, bool IsAnd,
948                                          const SimplifyQuery &Q,
949                                          InstCombiner::BuilderTy &Builder) {
950   Value *ZeroCmpOp;
951   ICmpInst::Predicate EqPred;
952   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
953       !ICmpInst::isEquality(EqPred))
954     return nullptr;
955 
956   auto IsKnownNonZero = [&](Value *V) {
957     return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
958   };
959 
960   ICmpInst::Predicate UnsignedPred;
961 
962   Value *A, *B;
963   if (match(UnsignedICmp,
964             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
965       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
966       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
967     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
968       if (!IsKnownNonZero(NonZero))
969         std::swap(NonZero, Other);
970       return IsKnownNonZero(NonZero);
971     };
972 
973     // Given  ZeroCmpOp = (A + B)
974     //   ZeroCmpOp <= A && ZeroCmpOp != 0  -->  (0-B) <  A
975     //   ZeroCmpOp >  A || ZeroCmpOp == 0  -->  (0-B) >= A
976     //
977     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
978     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
979     //     with X being the value (A/B) that is known to be non-zero,
980     //     and Y being remaining value.
981     if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
982         IsAnd)
983       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
984     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
985         IsAnd && GetKnownNonZeroAndOther(B, A))
986       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
987     if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
988         !IsAnd)
989       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
990     if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
991         !IsAnd && GetKnownNonZeroAndOther(B, A))
992       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
993   }
994 
995   Value *Base, *Offset;
996   if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
997     return nullptr;
998 
999   if (!match(UnsignedICmp,
1000              m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
1001       !ICmpInst::isUnsigned(UnsignedPred))
1002     return nullptr;
1003 
1004   // Base >=/> Offset && (Base - Offset) != 0  <-->  Base > Offset
1005   // (no overflow and not null)
1006   if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1007        UnsignedPred == ICmpInst::ICMP_UGT) &&
1008       EqPred == ICmpInst::ICMP_NE && IsAnd)
1009     return Builder.CreateICmpUGT(Base, Offset);
1010 
1011   // Base <=/< Offset || (Base - Offset) == 0  <-->  Base <= Offset
1012   // (overflow or null)
1013   if ((UnsignedPred == ICmpInst::ICMP_ULE ||
1014        UnsignedPred == ICmpInst::ICMP_ULT) &&
1015       EqPred == ICmpInst::ICMP_EQ && !IsAnd)
1016     return Builder.CreateICmpULE(Base, Offset);
1017 
1018   // Base <= Offset && (Base - Offset) != 0  -->  Base < Offset
1019   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1020       IsAnd)
1021     return Builder.CreateICmpULT(Base, Offset);
1022 
1023   // Base > Offset || (Base - Offset) == 0  -->  Base >= Offset
1024   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1025       !IsAnd)
1026     return Builder.CreateICmpUGE(Base, Offset);
1027 
1028   return nullptr;
1029 }
1030 
1031 struct IntPart {
1032   Value *From;
1033   unsigned StartBit;
1034   unsigned NumBits;
1035 };
1036 
1037 /// Match an extraction of bits from an integer.
1038 static Optional<IntPart> matchIntPart(Value *V) {
1039   Value *X;
1040   if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1041     return None;
1042 
1043   unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1044   unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1045   Value *Y;
1046   const APInt *Shift;
1047   // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1048   // from Y, not any shifted-in zeroes.
1049   if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1050       Shift->ule(NumOriginalBits - NumExtractedBits))
1051     return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1052   return {{X, 0, NumExtractedBits}};
1053 }
1054 
1055 /// Materialize an extraction of bits from an integer in IR.
1056 static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1057   Value *V = P.From;
1058   if (P.StartBit)
1059     V = Builder.CreateLShr(V, P.StartBit);
1060   Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1061   if (TruncTy != V->getType())
1062     V = Builder.CreateTrunc(V, TruncTy);
1063   return V;
1064 }
1065 
1066 /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1067 /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1068 /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1069 Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1070                                        bool IsAnd) {
1071   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1072     return nullptr;
1073 
1074   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1075   if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
1076     return nullptr;
1077 
1078   Optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
1079   Optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
1080   Optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
1081   Optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
1082   if (!L0 || !R0 || !L1 || !R1)
1083     return nullptr;
1084 
1085   // Make sure the LHS/RHS compare a part of the same value, possibly after
1086   // an operand swap.
1087   if (L0->From != L1->From || R0->From != R1->From) {
1088     if (L0->From != R1->From || R0->From != L1->From)
1089       return nullptr;
1090     std::swap(L1, R1);
1091   }
1092 
1093   // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1094   // the low part and L1/R1 being the high part.
1095   if (L0->StartBit + L0->NumBits != L1->StartBit ||
1096       R0->StartBit + R0->NumBits != R1->StartBit) {
1097     if (L1->StartBit + L1->NumBits != L0->StartBit ||
1098         R1->StartBit + R1->NumBits != R0->StartBit)
1099       return nullptr;
1100     std::swap(L0, L1);
1101     std::swap(R0, R1);
1102   }
1103 
1104   // We can simplify to a comparison of these larger parts of the integers.
1105   IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1106   IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1107   Value *LValue = extractIntPart(L, Builder);
1108   Value *RValue = extractIntPart(R, Builder);
1109   return Builder.CreateICmp(Pred, LValue, RValue);
1110 }
1111 
1112 /// Reduce logic-of-compares with equality to a constant by substituting a
1113 /// common operand with the constant. Callers are expected to call this with
1114 /// Cmp0/Cmp1 switched to handle logic op commutativity.
1115 static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1116                                           BinaryOperator &Logic,
1117                                           InstCombiner::BuilderTy &Builder,
1118                                           const SimplifyQuery &Q) {
1119   bool IsAnd = Logic.getOpcode() == Instruction::And;
1120   assert((IsAnd || Logic.getOpcode() == Instruction::Or) && "Wrong logic op");
1121 
1122   // Match an equality compare with a non-poison constant as Cmp0.
1123   // Also, give up if the compare can be constant-folded to avoid looping.
1124   ICmpInst::Predicate Pred0;
1125   Value *X;
1126   Constant *C;
1127   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1128       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
1129     return nullptr;
1130   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1131       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1132     return nullptr;
1133 
1134   // The other compare must include a common operand (X). Canonicalize the
1135   // common operand as operand 1 (Pred1 is swapped if the common operand was
1136   // operand 0).
1137   Value *Y;
1138   ICmpInst::Predicate Pred1;
1139   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
1140     return nullptr;
1141 
1142   // Replace variable with constant value equivalence to remove a variable use:
1143   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1144   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1145   // Can think of the 'or' substitution with the 'and' bool equivalent:
1146   // A || B --> A || (!A && B)
1147   Value *SubstituteCmp = SimplifyICmpInst(Pred1, Y, C, Q);
1148   if (!SubstituteCmp) {
1149     // If we need to create a new instruction, require that the old compare can
1150     // be removed.
1151     if (!Cmp1->hasOneUse())
1152       return nullptr;
1153     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
1154   }
1155   return Builder.CreateBinOp(Logic.getOpcode(), Cmp0, SubstituteCmp);
1156 }
1157 
1158 /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1159 /// or   (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1160 /// into a single comparison using range-based reasoning.
1161 static Value *foldAndOrOfICmpsUsingRanges(
1162     ICmpInst::Predicate Pred1, Value *V1, const APInt &C1,
1163     ICmpInst::Predicate Pred2, Value *V2, const APInt &C2,
1164     IRBuilderBase &Builder, bool IsAnd) {
1165   // Look through add of a constant offset on V1, V2, or both operands. This
1166   // allows us to interpret the V + C' < C'' range idiom into a proper range.
1167   const APInt *Offset1 = nullptr, *Offset2 = nullptr;
1168   if (V1 != V2) {
1169     Value *X;
1170     if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
1171       V1 = X;
1172     if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
1173       V2 = X;
1174   }
1175 
1176   if (V1 != V2)
1177     return nullptr;
1178 
1179   ConstantRange CR1 = ConstantRange::makeExactICmpRegion(Pred1, C1);
1180   if (Offset1)
1181     CR1 = CR1.subtract(*Offset1);
1182 
1183   ConstantRange CR2 = ConstantRange::makeExactICmpRegion(Pred2, C2);
1184   if (Offset2)
1185     CR2 = CR2.subtract(*Offset2);
1186 
1187   Optional<ConstantRange> CR =
1188       IsAnd ? CR1.exactIntersectWith(CR2) : CR1.exactUnionWith(CR2);
1189   if (!CR)
1190     return nullptr;
1191 
1192   CmpInst::Predicate NewPred;
1193   APInt NewC, Offset;
1194   CR->getEquivalentICmp(NewPred, NewC, Offset);
1195 
1196   Type *Ty = V1->getType();
1197   Value *NewV = V1;
1198   if (Offset != 0)
1199     NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
1200   return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
1201 }
1202 
1203 /// Fold (icmp)&(icmp) if possible.
1204 Value *InstCombinerImpl::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1205                                         BinaryOperator &And) {
1206   const SimplifyQuery Q = SQ.getWithInstruction(&And);
1207 
1208   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
1209   // if K1 and K2 are a one-bit mask.
1210   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &And,
1211                                                /* IsAnd */ true))
1212     return V;
1213 
1214   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1215 
1216   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1217   if (predicatesFoldable(PredL, PredR)) {
1218     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1219         LHS->getOperand(1) == RHS->getOperand(0))
1220       LHS->swapOperands();
1221     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1222         LHS->getOperand(1) == RHS->getOperand(1)) {
1223       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1224       unsigned Code =
1225           getICmpCode(LHS->getPredicate()) & getICmpCode(RHS->getPredicate());
1226       bool IsSigned = LHS->isSigned() || RHS->isSigned();
1227       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
1228     }
1229   }
1230 
1231   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
1232   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
1233     return V;
1234 
1235   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, And, Builder, Q))
1236     return V;
1237   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, And, Builder, Q))
1238     return V;
1239 
1240   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
1241   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
1242     return V;
1243 
1244   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
1245   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
1246     return V;
1247 
1248   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
1249     return V;
1250 
1251   if (Value *V = foldSignedTruncationCheck(LHS, RHS, And, Builder))
1252     return V;
1253 
1254   if (Value *V = foldIsPowerOf2(LHS, RHS, true /* JoinedByAnd */, Builder))
1255     return V;
1256 
1257   if (Value *X =
1258           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/true, Q, Builder))
1259     return X;
1260   if (Value *X =
1261           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/true, Q, Builder))
1262     return X;
1263 
1264   if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/true))
1265     return X;
1266 
1267   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
1268   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
1269 
1270   // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1271   // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs.
1272   if (PredL == ICmpInst::ICMP_EQ && match(LHS->getOperand(1), m_ZeroInt()) &&
1273       PredR == ICmpInst::ICMP_EQ && match(RHS->getOperand(1), m_ZeroInt()) &&
1274       LHS0->getType() == RHS0->getType()) {
1275     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1276     return Builder.CreateICmp(PredL, NewOr,
1277                               Constant::getNullValue(NewOr->getType()));
1278   }
1279 
1280   const APInt *LHSC, *RHSC;
1281   if (!match(LHS->getOperand(1), m_APInt(LHSC)) ||
1282       !match(RHS->getOperand(1), m_APInt(RHSC)))
1283     return nullptr;
1284 
1285   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
1286   // where CMAX is the all ones value for the truncated type,
1287   // iff the lower bits of C2 and CA are zero.
1288   if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
1289       RHS->hasOneUse()) {
1290     Value *V;
1291     const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
1292 
1293     // (trunc x) == C1 & (and x, CA) == C2
1294     // (and x, CA) == C2 & (trunc x) == C1
1295     if (match(RHS0, m_Trunc(m_Value(V))) &&
1296         match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
1297       SmallC = RHSC;
1298       BigC = LHSC;
1299     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
1300                match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
1301       SmallC = LHSC;
1302       BigC = RHSC;
1303     }
1304 
1305     if (SmallC && BigC) {
1306       unsigned BigBitSize = BigC->getBitWidth();
1307       unsigned SmallBitSize = SmallC->getBitWidth();
1308 
1309       // Check that the low bits are zero.
1310       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
1311       if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
1312         Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
1313         APInt N = SmallC->zext(BigBitSize) | *BigC;
1314         Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
1315         return Builder.CreateICmp(PredL, NewAnd, NewVal);
1316       }
1317     }
1318   }
1319 
1320   return foldAndOrOfICmpsUsingRanges(PredL, LHS0, *LHSC, PredR, RHS0, *RHSC,
1321                                      Builder, /* IsAnd */ true);
1322 }
1323 
1324 Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1325                                           bool IsAnd, bool IsLogicalSelect) {
1326   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1327   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1328   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1329 
1330   if (LHS0 == RHS1 && RHS0 == LHS1) {
1331     // Swap RHS operands to match LHS.
1332     PredR = FCmpInst::getSwappedPredicate(PredR);
1333     std::swap(RHS0, RHS1);
1334   }
1335 
1336   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1337   // Suppose the relation between x and y is R, where R is one of
1338   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1339   // testing the desired relations.
1340   //
1341   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1342   //    bool(R & CC0) && bool(R & CC1)
1343   //  = bool((R & CC0) & (R & CC1))
1344   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1345   //
1346   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1347   //    bool(R & CC0) || bool(R & CC1)
1348   //  = bool((R & CC0) | (R & CC1))
1349   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1350   if (LHS0 == RHS0 && LHS1 == RHS1) {
1351     unsigned FCmpCodeL = getFCmpCode(PredL);
1352     unsigned FCmpCodeR = getFCmpCode(PredR);
1353     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1354 
1355     // Intersect the fast math flags.
1356     // TODO: We can union the fast math flags unless this is a logical select.
1357     IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1358     FastMathFlags FMF = LHS->getFastMathFlags();
1359     FMF &= RHS->getFastMathFlags();
1360     Builder.setFastMathFlags(FMF);
1361 
1362     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1363   }
1364 
1365   // This transform is not valid for a logical select.
1366   if (!IsLogicalSelect &&
1367       ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1368        (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
1369         !IsAnd))) {
1370     if (LHS0->getType() != RHS0->getType())
1371       return nullptr;
1372 
1373     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1374     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1375     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
1376       // Ignore the constants because they are obviously not NANs:
1377       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
1378       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
1379       return Builder.CreateFCmp(PredL, LHS0, RHS0);
1380   }
1381 
1382   return nullptr;
1383 }
1384 
1385 /// This a limited reassociation for a special case (see above) where we are
1386 /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1387 /// This could be handled more generally in '-reassociation', but it seems like
1388 /// an unlikely pattern for a large number of logic ops and fcmps.
1389 static Instruction *reassociateFCmps(BinaryOperator &BO,
1390                                      InstCombiner::BuilderTy &Builder) {
1391   Instruction::BinaryOps Opcode = BO.getOpcode();
1392   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1393          "Expecting and/or op for fcmp transform");
1394 
1395   // There are 4 commuted variants of the pattern. Canonicalize operands of this
1396   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1397   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
1398   FCmpInst::Predicate Pred;
1399   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
1400     std::swap(Op0, Op1);
1401 
1402   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1403   Value *BO10, *BO11;
1404   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1405                                                            : FCmpInst::FCMP_UNO;
1406   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1407       !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
1408     return nullptr;
1409 
1410   // The inner logic op must have a matching fcmp operand.
1411   Value *Y;
1412   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1413       Pred != NanPred || X->getType() != Y->getType())
1414     std::swap(BO10, BO11);
1415 
1416   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1417       Pred != NanPred || X->getType() != Y->getType())
1418     return nullptr;
1419 
1420   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1421   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
1422   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
1423   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
1424     // Intersect FMF from the 2 source fcmps.
1425     NewFCmpInst->copyIRFlags(Op0);
1426     NewFCmpInst->andIRFlags(BO10);
1427   }
1428   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
1429 }
1430 
1431 /// Match variations of De Morgan's Laws:
1432 /// (~A & ~B) == (~(A | B))
1433 /// (~A | ~B) == (~(A & B))
1434 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1435                                        InstCombiner::BuilderTy &Builder) {
1436   const Instruction::BinaryOps Opcode = I.getOpcode();
1437   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1438          "Trying to match De Morgan's Laws with something other than and/or");
1439 
1440   // Flip the logic operation.
1441   const Instruction::BinaryOps FlippedOpcode =
1442       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1443 
1444   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1445   Value *A, *B;
1446   if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1447       match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
1448       !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
1449       !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
1450     Value *AndOr =
1451         Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
1452     return BinaryOperator::CreateNot(AndOr);
1453   }
1454 
1455   // The 'not' ops may require reassociation.
1456   // (A & ~B) & ~C --> A & ~(B | C)
1457   // (~B & A) & ~C --> A & ~(B | C)
1458   // (A | ~B) | ~C --> A | ~(B & C)
1459   // (~B | A) | ~C --> A | ~(B & C)
1460   Value *C;
1461   if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
1462       match(Op1, m_Not(m_Value(C)))) {
1463     Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
1464     return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
1465   }
1466 
1467   return nullptr;
1468 }
1469 
1470 bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1471   Value *CastSrc = CI->getOperand(0);
1472 
1473   // Noop casts and casts of constants should be eliminated trivially.
1474   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1475     return false;
1476 
1477   // If this cast is paired with another cast that can be eliminated, we prefer
1478   // to have it eliminated.
1479   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1480     if (isEliminableCastPair(PrecedingCI, CI))
1481       return false;
1482 
1483   return true;
1484 }
1485 
1486 /// Fold {and,or,xor} (cast X), C.
1487 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1488                                           InstCombiner::BuilderTy &Builder) {
1489   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1490   if (!C)
1491     return nullptr;
1492 
1493   auto LogicOpc = Logic.getOpcode();
1494   Type *DestTy = Logic.getType();
1495   Type *SrcTy = Cast->getSrcTy();
1496 
1497   // Move the logic operation ahead of a zext or sext if the constant is
1498   // unchanged in the smaller source type. Performing the logic in a smaller
1499   // type may provide more information to later folds, and the smaller logic
1500   // instruction may be cheaper (particularly in the case of vectors).
1501   Value *X;
1502   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1503     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1504     Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1505     if (ZextTruncC == C) {
1506       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1507       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1508       return new ZExtInst(NewOp, DestTy);
1509     }
1510   }
1511 
1512   if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1513     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1514     Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1515     if (SextTruncC == C) {
1516       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1517       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1518       return new SExtInst(NewOp, DestTy);
1519     }
1520   }
1521 
1522   return nullptr;
1523 }
1524 
1525 /// Fold {and,or,xor} (cast X), Y.
1526 Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1527   auto LogicOpc = I.getOpcode();
1528   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1529 
1530   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1531   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1532   if (!Cast0)
1533     return nullptr;
1534 
1535   // This must be a cast from an integer or integer vector source type to allow
1536   // transformation of the logic operation to the source type.
1537   Type *DestTy = I.getType();
1538   Type *SrcTy = Cast0->getSrcTy();
1539   if (!SrcTy->isIntOrIntVectorTy())
1540     return nullptr;
1541 
1542   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1543     return Ret;
1544 
1545   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1546   if (!Cast1)
1547     return nullptr;
1548 
1549   // Both operands of the logic operation are casts. The casts must be of the
1550   // same type for reduction.
1551   auto CastOpcode = Cast0->getOpcode();
1552   if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1553     return nullptr;
1554 
1555   Value *Cast0Src = Cast0->getOperand(0);
1556   Value *Cast1Src = Cast1->getOperand(0);
1557 
1558   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1559   if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1560     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1561                                         I.getName());
1562     return CastInst::Create(CastOpcode, NewOp, DestTy);
1563   }
1564 
1565   // For now, only 'and'/'or' have optimizations after this.
1566   if (LogicOpc == Instruction::Xor)
1567     return nullptr;
1568 
1569   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1570   // cast is otherwise not optimizable.  This happens for vector sexts.
1571   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1572   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1573   if (ICmp0 && ICmp1) {
1574     Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
1575                                               : foldOrOfICmps(ICmp0, ICmp1, I);
1576     if (Res)
1577       return CastInst::Create(CastOpcode, Res, DestTy);
1578     return nullptr;
1579   }
1580 
1581   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1582   // cast is otherwise not optimizable.  This happens for vector sexts.
1583   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1584   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1585   if (FCmp0 && FCmp1)
1586     if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1587       return CastInst::Create(CastOpcode, R, DestTy);
1588 
1589   return nullptr;
1590 }
1591 
1592 static Instruction *foldAndToXor(BinaryOperator &I,
1593                                  InstCombiner::BuilderTy &Builder) {
1594   assert(I.getOpcode() == Instruction::And);
1595   Value *Op0 = I.getOperand(0);
1596   Value *Op1 = I.getOperand(1);
1597   Value *A, *B;
1598 
1599   // Operand complexity canonicalization guarantees that the 'or' is Op0.
1600   // (A | B) & ~(A & B) --> A ^ B
1601   // (A | B) & ~(B & A) --> A ^ B
1602   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1603                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
1604     return BinaryOperator::CreateXor(A, B);
1605 
1606   // (A | ~B) & (~A | B) --> ~(A ^ B)
1607   // (A | ~B) & (B | ~A) --> ~(A ^ B)
1608   // (~B | A) & (~A | B) --> ~(A ^ B)
1609   // (~B | A) & (B | ~A) --> ~(A ^ B)
1610   if (Op0->hasOneUse() || Op1->hasOneUse())
1611     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
1612                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
1613       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1614 
1615   return nullptr;
1616 }
1617 
1618 static Instruction *foldOrToXor(BinaryOperator &I,
1619                                 InstCombiner::BuilderTy &Builder) {
1620   assert(I.getOpcode() == Instruction::Or);
1621   Value *Op0 = I.getOperand(0);
1622   Value *Op1 = I.getOperand(1);
1623   Value *A, *B;
1624 
1625   // Operand complexity canonicalization guarantees that the 'and' is Op0.
1626   // (A & B) | ~(A | B) --> ~(A ^ B)
1627   // (A & B) | ~(B | A) --> ~(A ^ B)
1628   if (Op0->hasOneUse() || Op1->hasOneUse())
1629     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1630         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1631       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1632 
1633   // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1634   // (A ^ B) | ~(A | B) --> ~(A & B)
1635   // (A ^ B) | ~(B | A) --> ~(A & B)
1636   if (Op0->hasOneUse() || Op1->hasOneUse())
1637     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1638         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1639       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1640 
1641   // (A & ~B) | (~A & B) --> A ^ B
1642   // (A & ~B) | (B & ~A) --> A ^ B
1643   // (~B & A) | (~A & B) --> A ^ B
1644   // (~B & A) | (B & ~A) --> A ^ B
1645   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1646       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1647     return BinaryOperator::CreateXor(A, B);
1648 
1649   return nullptr;
1650 }
1651 
1652 /// Return true if a constant shift amount is always less than the specified
1653 /// bit-width. If not, the shift could create poison in the narrower type.
1654 static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1655   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1656   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
1657 }
1658 
1659 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1660 /// a common zext operand: and (binop (zext X), C), (zext X).
1661 Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
1662   // This transform could also apply to {or, and, xor}, but there are better
1663   // folds for those cases, so we don't expect those patterns here. AShr is not
1664   // handled because it should always be transformed to LShr in this sequence.
1665   // The subtract transform is different because it has a constant on the left.
1666   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1667   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1668   Constant *C;
1669   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1670       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1671       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1672       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1673       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1674     return nullptr;
1675 
1676   Value *X;
1677   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
1678     return nullptr;
1679 
1680   Type *Ty = And.getType();
1681   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1682     return nullptr;
1683 
1684   // If we're narrowing a shift, the shift amount must be safe (less than the
1685   // width) in the narrower type. If the shift amount is greater, instsimplify
1686   // usually handles that case, but we can't guarantee/assert it.
1687   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1688   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1689     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1690       return nullptr;
1691 
1692   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1693   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1694   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1695   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1696                                          : Builder.CreateBinOp(Opc, X, NewC);
1697   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1698 }
1699 
1700 /// Try folding relatively complex patterns for both And and Or operations
1701 /// with all And and Or swapped.
1702 static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
1703                                              InstCombiner::BuilderTy &Builder) {
1704   const Instruction::BinaryOps Opcode = I.getOpcode();
1705   assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1706 
1707   // Flip the logic operation.
1708   const Instruction::BinaryOps FlippedOpcode =
1709       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1710 
1711   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1712   Value *A, *B, *C, *X, *Y, *Dummy;
1713 
1714   // Match following expressions:
1715   // (~(A | B) & C)
1716   // (~(A & B) | C)
1717   // Captures X = ~(A | B) or ~(A & B)
1718   const auto matchNotOrAnd =
1719       [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
1720                               Value *&X, bool CountUses = false) -> bool {
1721     if (CountUses && !Op->hasOneUse())
1722       return false;
1723 
1724     if (match(Op, m_c_BinOp(FlippedOpcode,
1725                             m_CombineAnd(m_Value(X),
1726                                          m_Not(m_c_BinOp(Opcode, m_A, m_B))),
1727                             m_C)))
1728       return !CountUses || X->hasOneUse();
1729 
1730     return false;
1731   };
1732 
1733   // (~(A | B) & C) | ... --> ...
1734   // (~(A & B) | C) & ... --> ...
1735   // TODO: One use checks are conservative. We just need to check that a total
1736   //       number of multiple used values does not exceed reduction
1737   //       in operations.
1738   if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
1739     // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
1740     // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
1741     if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
1742                       true)) {
1743       Value *Xor = Builder.CreateXor(B, C);
1744       return (Opcode == Instruction::Or)
1745                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
1746                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
1747     }
1748 
1749     // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
1750     // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
1751     if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
1752                       true)) {
1753       Value *Xor = Builder.CreateXor(A, C);
1754       return (Opcode == Instruction::Or)
1755                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
1756                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
1757     }
1758 
1759     // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
1760     // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
1761     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1762                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
1763       return BinaryOperator::CreateNot(Builder.CreateBinOp(
1764           Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
1765 
1766     // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
1767     // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
1768     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1769                        m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
1770       return BinaryOperator::CreateNot(Builder.CreateBinOp(
1771           Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
1772 
1773     // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
1774     // Note, the pattern with swapped and/or is not handled because the
1775     // result is more undefined than a source:
1776     // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
1777     if (Opcode == Instruction::Or && Op0->hasOneUse() &&
1778         match(Op1, m_OneUse(m_Not(m_CombineAnd(
1779                        m_Value(Y),
1780                        m_c_BinOp(Opcode, m_Specific(C),
1781                                  m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
1782       // X = ~(A | B)
1783       // Y = (C | (A ^ B)
1784       Value *Or = cast<BinaryOperator>(X)->getOperand(0);
1785       return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
1786     }
1787   }
1788 
1789   // (~A & B & C) | ... --> ...
1790   // (~A | B | C) | ... --> ...
1791   // TODO: One use checks are conservative. We just need to check that a total
1792   //       number of multiple used values does not exceed reduction
1793   //       in operations.
1794   if (match(Op0,
1795             m_OneUse(m_c_BinOp(FlippedOpcode,
1796                                m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
1797                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
1798       match(Op0, m_OneUse(m_c_BinOp(
1799                      FlippedOpcode,
1800                      m_c_BinOp(FlippedOpcode, m_Value(C),
1801                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
1802                      m_Value(B))))) {
1803     // X = ~A
1804     // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
1805     // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
1806     if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
1807                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
1808                        m_Specific(C))))) ||
1809         match(Op1, m_OneUse(m_Not(m_c_BinOp(
1810                        Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
1811                        m_Specific(A))))) ||
1812         match(Op1, m_OneUse(m_Not(m_c_BinOp(
1813                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
1814                        m_Specific(B)))))) {
1815       Value *Xor = Builder.CreateXor(B, C);
1816       return (Opcode == Instruction::Or)
1817                  ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
1818                  : BinaryOperator::CreateOr(Xor, X);
1819     }
1820 
1821     // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
1822     // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
1823     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1824                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
1825       return BinaryOperator::Create(
1826           FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
1827           X);
1828 
1829     // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
1830     // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
1831     if (match(Op1, m_OneUse(m_Not(m_OneUse(
1832                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
1833       return BinaryOperator::Create(
1834           FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
1835           X);
1836   }
1837 
1838   return nullptr;
1839 }
1840 
1841 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1842 // here. We should standardize that construct where it is needed or choose some
1843 // other way to ensure that commutated variants of patterns are not missed.
1844 Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
1845   Type *Ty = I.getType();
1846 
1847   if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1),
1848                                  SQ.getWithInstruction(&I)))
1849     return replaceInstUsesWith(I, V);
1850 
1851   if (SimplifyAssociativeOrCommutative(I))
1852     return &I;
1853 
1854   if (Instruction *X = foldVectorBinop(I))
1855     return X;
1856 
1857   if (Instruction *Phi = foldBinopWithPhiOperands(I))
1858     return Phi;
1859 
1860   // See if we can simplify any instructions used by the instruction whose sole
1861   // purpose is to compute bits we don't care about.
1862   if (SimplifyDemandedInstructionBits(I))
1863     return &I;
1864 
1865   // Do this before using distributive laws to catch simple and/or/not patterns.
1866   if (Instruction *Xor = foldAndToXor(I, Builder))
1867     return Xor;
1868 
1869   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
1870     return X;
1871 
1872   // (A|B)&(A|C) -> A|(B&C) etc
1873   if (Value *V = SimplifyUsingDistributiveLaws(I))
1874     return replaceInstUsesWith(I, V);
1875 
1876   if (Value *V = SimplifyBSwap(I, Builder))
1877     return replaceInstUsesWith(I, V);
1878 
1879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1880 
1881   Value *X, *Y;
1882   if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1883       match(Op1, m_One())) {
1884     // (1 << X) & 1 --> zext(X == 0)
1885     // (1 >> X) & 1 --> zext(X == 0)
1886     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
1887     return new ZExtInst(IsZero, Ty);
1888   }
1889 
1890   const APInt *C;
1891   if (match(Op1, m_APInt(C))) {
1892     const APInt *XorC;
1893     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1894       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1895       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
1896       Value *And = Builder.CreateAnd(X, Op1);
1897       And->takeName(Op0);
1898       return BinaryOperator::CreateXor(And, NewC);
1899     }
1900 
1901     const APInt *OrC;
1902     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1903       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1904       // NOTE: This reduces the number of bits set in the & mask, which
1905       // can expose opportunities for store narrowing for scalars.
1906       // NOTE: SimplifyDemandedBits should have already removed bits from C1
1907       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1908       // above, but this feels safer.
1909       APInt Together = *C & *OrC;
1910       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
1911       And->takeName(Op0);
1912       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
1913     }
1914 
1915     // If the mask is only needed on one incoming arm, push the 'and' op up.
1916     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1917         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1918       APInt NotAndMask(~(*C));
1919       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1920       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1921         // Not masking anything out for the LHS, move mask to RHS.
1922         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1923         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1924         return BinaryOperator::Create(BinOp, X, NewRHS);
1925       }
1926       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1927         // Not masking anything out for the RHS, move mask to LHS.
1928         // and ({x}or X, Y), C --> {x}or (and X, C), Y
1929         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1930         return BinaryOperator::Create(BinOp, NewLHS, Y);
1931       }
1932     }
1933 
1934     unsigned Width = Ty->getScalarSizeInBits();
1935     const APInt *ShiftC;
1936     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC)))))) {
1937       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
1938         // We are clearing high bits that were potentially set by sext+ashr:
1939         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
1940         Value *Sext = Builder.CreateSExt(X, Ty);
1941         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
1942         return BinaryOperator::CreateLShr(Sext, ShAmtC);
1943       }
1944     }
1945 
1946     const APInt *AddC;
1947     if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
1948       // If we add zeros to every bit below a mask, the add has no effect:
1949       // (X + AddC) & LowMaskC --> X & LowMaskC
1950       unsigned Ctlz = C->countLeadingZeros();
1951       APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
1952       if ((*AddC & LowMask).isZero())
1953         return BinaryOperator::CreateAnd(X, Op1);
1954 
1955       // If we are masking the result of the add down to exactly one bit and
1956       // the constant we are adding has no bits set below that bit, then the
1957       // add is flipping a single bit. Example:
1958       // (X + 4) & 4 --> (X & 4) ^ 4
1959       if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
1960         assert((*C & *AddC) != 0 && "Expected common bit");
1961         Value *NewAnd = Builder.CreateAnd(X, Op1);
1962         return BinaryOperator::CreateXor(NewAnd, Op1);
1963       }
1964     }
1965 
1966     // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
1967     // bitwidth of X and OP behaves well when given trunc(C1) and X.
1968     auto isSuitableBinOpcode = [](BinaryOperator *B) {
1969       switch (B->getOpcode()) {
1970       case Instruction::Xor:
1971       case Instruction::Or:
1972       case Instruction::Mul:
1973       case Instruction::Add:
1974       case Instruction::Sub:
1975         return true;
1976       default:
1977         return false;
1978       }
1979     };
1980     BinaryOperator *BO;
1981     if (match(Op0, m_OneUse(m_BinOp(BO))) && isSuitableBinOpcode(BO)) {
1982       Value *X;
1983       const APInt *C1;
1984       // TODO: The one-use restrictions could be relaxed a little if the AND
1985       // is going to be removed.
1986       if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
1987           C->isIntN(X->getType()->getScalarSizeInBits())) {
1988         unsigned XWidth = X->getType()->getScalarSizeInBits();
1989         Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
1990         Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
1991                            ? Builder.CreateBinOp(BO->getOpcode(), X, TruncC1)
1992                            : Builder.CreateBinOp(BO->getOpcode(), TruncC1, X);
1993         Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
1994         Value *And = Builder.CreateAnd(BinOp, TruncC);
1995         return new ZExtInst(And, Ty);
1996       }
1997     }
1998   }
1999 
2000   if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
2001                       m_SignMask())) &&
2002       match(Y, m_SpecificInt_ICMP(
2003                    ICmpInst::Predicate::ICMP_EQ,
2004                    APInt(Ty->getScalarSizeInBits(),
2005                          Ty->getScalarSizeInBits() -
2006                              X->getType()->getScalarSizeInBits())))) {
2007     auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
2008     auto *SanitizedSignMask = cast<Constant>(Op1);
2009     // We must be careful with the undef elements of the sign bit mask, however:
2010     // the mask elt can be undef iff the shift amount for that lane was undef,
2011     // otherwise we need to sanitize undef masks to zero.
2012     SanitizedSignMask = Constant::replaceUndefsWith(
2013         SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
2014     SanitizedSignMask =
2015         Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
2016     return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
2017   }
2018 
2019   if (Instruction *Z = narrowMaskedBinOp(I))
2020     return Z;
2021 
2022   if (I.getType()->isIntOrIntVectorTy(1)) {
2023     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
2024       if (auto *I =
2025               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
2026         return I;
2027     }
2028     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
2029       if (auto *I =
2030               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
2031         return I;
2032     }
2033   }
2034 
2035   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2036     return FoldedLogic;
2037 
2038   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2039     return DeMorgan;
2040 
2041   {
2042     Value *A, *B, *C;
2043     // A & (A ^ B) --> A & ~B
2044     if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2045       return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
2046     // (A ^ B) & A --> A & ~B
2047     if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2048       return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
2049 
2050     // A & ~(A ^ B) --> A & B
2051     if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2052       return BinaryOperator::CreateAnd(Op0, B);
2053     // ~(A ^ B) & A --> A & B
2054     if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2055       return BinaryOperator::CreateAnd(Op1, B);
2056 
2057     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
2058     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2059       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2060         if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2061           return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
2062 
2063     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
2064     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2065       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2066         if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2067           return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
2068 
2069     // (A | B) & (~A ^ B) -> A & B
2070     // (A | B) & (B ^ ~A) -> A & B
2071     // (B | A) & (~A ^ B) -> A & B
2072     // (B | A) & (B ^ ~A) -> A & B
2073     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2074         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2075       return BinaryOperator::CreateAnd(A, B);
2076 
2077     // (~A ^ B) & (A | B) -> A & B
2078     // (~A ^ B) & (B | A) -> A & B
2079     // (B ^ ~A) & (A | B) -> A & B
2080     // (B ^ ~A) & (B | A) -> A & B
2081     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2082         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2083       return BinaryOperator::CreateAnd(A, B);
2084 
2085     // (~A | B) & (A ^ B) -> ~A & B
2086     // (~A | B) & (B ^ A) -> ~A & B
2087     // (B | ~A) & (A ^ B) -> ~A & B
2088     // (B | ~A) & (B ^ A) -> ~A & B
2089     if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2090         match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2091       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2092 
2093     // (A ^ B) & (~A | B) -> ~A & B
2094     // (B ^ A) & (~A | B) -> ~A & B
2095     // (A ^ B) & (B | ~A) -> ~A & B
2096     // (B ^ A) & (B | ~A) -> ~A & B
2097     if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2098         match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
2099       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
2100   }
2101 
2102   {
2103     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2104     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2105     if (LHS && RHS)
2106       if (Value *Res = foldAndOfICmps(LHS, RHS, I))
2107         return replaceInstUsesWith(I, Res);
2108 
2109     // TODO: Make this recursive; it's a little tricky because an arbitrary
2110     // number of 'and' instructions might have to be created.
2111     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
2112       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2113         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
2114           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
2115       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2116         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
2117           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
2118     }
2119     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
2120       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2121         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
2122           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
2123       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2124         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
2125           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
2126     }
2127   }
2128 
2129   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2130     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2131       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
2132         return replaceInstUsesWith(I, Res);
2133 
2134   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2135     return FoldedFCmps;
2136 
2137   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
2138     return CastedAnd;
2139 
2140   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
2141     return Sel;
2142 
2143   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
2144   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
2145   //       with binop identity constant. But creating a select with non-constant
2146   //       arm may not be reversible due to poison semantics. Is that a good
2147   //       canonicalization?
2148   Value *A;
2149   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2150       A->getType()->isIntOrIntVectorTy(1))
2151     return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
2152   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2153       A->getType()->isIntOrIntVectorTy(1))
2154     return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
2155 
2156   // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0
2157   unsigned FullShift = Ty->getScalarSizeInBits() - 1;
2158   if (match(&I, m_c_And(m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))),
2159                         m_Value(Y)))) {
2160     Constant *Zero = ConstantInt::getNullValue(Ty);
2161     Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg");
2162     return SelectInst::Create(Cmp, Y, Zero);
2163   }
2164   // If there's a 'not' of the shifted value, swap the select operands:
2165   // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y
2166   if (match(&I, m_c_And(m_OneUse(m_Not(
2167                             m_AShr(m_Value(X), m_SpecificInt(FullShift)))),
2168                         m_Value(Y)))) {
2169     Constant *Zero = ConstantInt::getNullValue(Ty);
2170     Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg");
2171     return SelectInst::Create(Cmp, Zero, Y);
2172   }
2173 
2174   // (~x) & y  -->  ~(x | (~y))  iff that gets rid of inversions
2175   if (sinkNotIntoOtherHandOfAndOrOr(I))
2176     return &I;
2177 
2178   // An and recurrence w/loop invariant step is equivelent to (and start, step)
2179   PHINode *PN = nullptr;
2180   Value *Start = nullptr, *Step = nullptr;
2181   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2182     return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2183 
2184   return nullptr;
2185 }
2186 
2187 Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2188                                                       bool MatchBSwaps,
2189                                                       bool MatchBitReversals) {
2190   SmallVector<Instruction *, 4> Insts;
2191   if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2192                                        Insts))
2193     return nullptr;
2194   Instruction *LastInst = Insts.pop_back_val();
2195   LastInst->removeFromParent();
2196 
2197   for (auto *Inst : Insts)
2198     Worklist.push(Inst);
2199   return LastInst;
2200 }
2201 
2202 /// Match UB-safe variants of the funnel shift intrinsic.
2203 static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
2204   // TODO: Can we reduce the code duplication between this and the related
2205   // rotate matching code under visitSelect and visitTrunc?
2206   unsigned Width = Or.getType()->getScalarSizeInBits();
2207 
2208   // First, find an or'd pair of opposite shifts:
2209   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2210   BinaryOperator *Or0, *Or1;
2211   if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
2212       !match(Or.getOperand(1), m_BinOp(Or1)))
2213     return nullptr;
2214 
2215   Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2216   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
2217       !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2218       Or0->getOpcode() == Or1->getOpcode())
2219     return nullptr;
2220 
2221   // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2222   if (Or0->getOpcode() == BinaryOperator::LShr) {
2223     std::swap(Or0, Or1);
2224     std::swap(ShVal0, ShVal1);
2225     std::swap(ShAmt0, ShAmt1);
2226   }
2227   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2228          Or1->getOpcode() == BinaryOperator::LShr &&
2229          "Illegal or(shift,shift) pair");
2230 
2231   // Match the shift amount operands for a funnel shift pattern. This always
2232   // matches a subtraction on the R operand.
2233   auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2234     // Check for constant shift amounts that sum to the bitwidth.
2235     const APInt *LI, *RI;
2236     if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
2237       if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2238         return ConstantInt::get(L->getType(), *LI);
2239 
2240     Constant *LC, *RC;
2241     if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
2242         match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2243         match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2244         match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
2245       return ConstantExpr::mergeUndefsWith(LC, RC);
2246 
2247     // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
2248     // We limit this to X < Width in case the backend re-expands the intrinsic,
2249     // and has to reintroduce a shift modulo operation (InstCombine might remove
2250     // it after this fold). This still doesn't guarantee that the final codegen
2251     // will match this original pattern.
2252     if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2253       KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
2254       return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2255     }
2256 
2257     // For non-constant cases, the following patterns currently only work for
2258     // rotation patterns.
2259     // TODO: Add general funnel-shift compatible patterns.
2260     if (ShVal0 != ShVal1)
2261       return nullptr;
2262 
2263     // For non-constant cases we don't support non-pow2 shift masks.
2264     // TODO: Is it worth matching urem as well?
2265     if (!isPowerOf2_32(Width))
2266       return nullptr;
2267 
2268     // The shift amount may be masked with negation:
2269     // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2270     Value *X;
2271     unsigned Mask = Width - 1;
2272     if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
2273         match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
2274       return X;
2275 
2276     // Similar to above, but the shift amount may be extended after masking,
2277     // so return the extended value as the parameter for the intrinsic.
2278     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2279         match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
2280                        m_SpecificInt(Mask))))
2281       return L;
2282 
2283     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2284         match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
2285       return L;
2286 
2287     return nullptr;
2288   };
2289 
2290   Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
2291   bool IsFshl = true; // Sub on LSHR.
2292   if (!ShAmt) {
2293     ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2294     IsFshl = false; // Sub on SHL.
2295   }
2296   if (!ShAmt)
2297     return nullptr;
2298 
2299   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2300   Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
2301   return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
2302 }
2303 
2304 /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
2305 static Instruction *matchOrConcat(Instruction &Or,
2306                                   InstCombiner::BuilderTy &Builder) {
2307   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
2308   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
2309   Type *Ty = Or.getType();
2310 
2311   unsigned Width = Ty->getScalarSizeInBits();
2312   if ((Width & 1) != 0)
2313     return nullptr;
2314   unsigned HalfWidth = Width / 2;
2315 
2316   // Canonicalize zext (lower half) to LHS.
2317   if (!isa<ZExtInst>(Op0))
2318     std::swap(Op0, Op1);
2319 
2320   // Find lower/upper half.
2321   Value *LowerSrc, *ShlVal, *UpperSrc;
2322   const APInt *C;
2323   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
2324       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
2325       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
2326     return nullptr;
2327   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
2328       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
2329     return nullptr;
2330 
2331   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
2332     Value *NewLower = Builder.CreateZExt(Lo, Ty);
2333     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
2334     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
2335     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
2336     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
2337     return Builder.CreateCall(F, BinOp);
2338   };
2339 
2340   // BSWAP: Push the concat down, swapping the lower/upper sources.
2341   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
2342   Value *LowerBSwap, *UpperBSwap;
2343   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
2344       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
2345     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
2346 
2347   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
2348   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
2349   Value *LowerBRev, *UpperBRev;
2350   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
2351       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
2352     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
2353 
2354   return nullptr;
2355 }
2356 
2357 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
2358 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
2359   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
2360   for (unsigned i = 0; i != NumElts; ++i) {
2361     Constant *EltC1 = C1->getAggregateElement(i);
2362     Constant *EltC2 = C2->getAggregateElement(i);
2363     if (!EltC1 || !EltC2)
2364       return false;
2365 
2366     // One element must be all ones, and the other must be all zeros.
2367     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
2368           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
2369       return false;
2370   }
2371   return true;
2372 }
2373 
2374 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
2375 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
2376 /// B, it can be used as the condition operand of a select instruction.
2377 Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) {
2378   // We may have peeked through bitcasts in the caller.
2379   // Exit immediately if we don't have (vector) integer types.
2380   Type *Ty = A->getType();
2381   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
2382     return nullptr;
2383 
2384   // If A is the 'not' operand of B and has enough signbits, we have our answer.
2385   if (match(B, m_Not(m_Specific(A)))) {
2386     // If these are scalars or vectors of i1, A can be used directly.
2387     if (Ty->isIntOrIntVectorTy(1))
2388       return A;
2389 
2390     // If we look through a vector bitcast, the caller will bitcast the operands
2391     // to match the condition's number of bits (N x i1).
2392     // To make this poison-safe, disallow bitcast from wide element to narrow
2393     // element. That could allow poison in lanes where it was not present in the
2394     // original code.
2395     A = peekThroughBitcast(A);
2396     if (A->getType()->isIntOrIntVectorTy()) {
2397       unsigned NumSignBits = ComputeNumSignBits(A);
2398       if (NumSignBits == A->getType()->getScalarSizeInBits() &&
2399           NumSignBits <= Ty->getScalarSizeInBits())
2400         return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
2401     }
2402     return nullptr;
2403   }
2404 
2405   // If both operands are constants, see if the constants are inverse bitmasks.
2406   Constant *AConst, *BConst;
2407   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
2408     if (AConst == ConstantExpr::getNot(BConst) &&
2409         ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
2410       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
2411 
2412   // Look for more complex patterns. The 'not' op may be hidden behind various
2413   // casts. Look through sexts and bitcasts to find the booleans.
2414   Value *Cond;
2415   Value *NotB;
2416   if (match(A, m_SExt(m_Value(Cond))) &&
2417       Cond->getType()->isIntOrIntVectorTy(1)) {
2418     // A = sext i1 Cond; B = sext (not (i1 Cond))
2419     if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
2420       return Cond;
2421 
2422     // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
2423     // TODO: The one-use checks are unnecessary or misplaced. If the caller
2424     //       checked for uses on logic ops/casts, that should be enough to
2425     //       make this transform worthwhile.
2426     if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
2427       NotB = peekThroughBitcast(NotB, true);
2428       if (match(NotB, m_SExt(m_Specific(Cond))))
2429         return Cond;
2430     }
2431   }
2432 
2433   // All scalar (and most vector) possibilities should be handled now.
2434   // Try more matches that only apply to non-splat constant vectors.
2435   if (!Ty->isVectorTy())
2436     return nullptr;
2437 
2438   // If both operands are xor'd with constants using the same sexted boolean
2439   // operand, see if the constants are inverse bitmasks.
2440   // TODO: Use ConstantExpr::getNot()?
2441   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
2442       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
2443       Cond->getType()->isIntOrIntVectorTy(1) &&
2444       areInverseVectorBitmasks(AConst, BConst)) {
2445     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
2446     return Builder.CreateXor(Cond, AConst);
2447   }
2448   return nullptr;
2449 }
2450 
2451 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2452 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2453 Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
2454                                               Value *D) {
2455   // The potential condition of the select may be bitcasted. In that case, look
2456   // through its bitcast and the corresponding bitcast of the 'not' condition.
2457   Type *OrigType = A->getType();
2458   A = peekThroughBitcast(A, true);
2459   B = peekThroughBitcast(B, true);
2460   if (Value *Cond = getSelectCondition(A, B)) {
2461     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2462     // If this is a vector, we may need to cast to match the condition's length.
2463     // The bitcasts will either all exist or all not exist. The builder will
2464     // not create unnecessary casts if the types already match.
2465     Type *SelTy = A->getType();
2466     if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
2467       unsigned Elts = VecTy->getElementCount().getKnownMinValue();
2468       Type *EltTy = Builder.getIntNTy(SelTy->getPrimitiveSizeInBits() / Elts);
2469       SelTy = VectorType::get(EltTy, VecTy->getElementCount());
2470     }
2471     Value *BitcastC = Builder.CreateBitCast(C, SelTy);
2472     Value *BitcastD = Builder.CreateBitCast(D, SelTy);
2473     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
2474     return Builder.CreateBitCast(Select, OrigType);
2475   }
2476 
2477   return nullptr;
2478 }
2479 
2480 /// Fold (icmp)|(icmp) if possible.
2481 Value *InstCombinerImpl::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
2482                                        BinaryOperator &Or) {
2483   const SimplifyQuery Q = SQ.getWithInstruction(&Or);
2484 
2485   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
2486   // if K1 and K2 are a one-bit mask.
2487   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &Or,
2488                                                /* IsAnd */ false))
2489     return V;
2490 
2491   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2492   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
2493   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
2494   const APInt *LHSC = nullptr, *RHSC = nullptr;
2495   match(LHS1, m_APInt(LHSC));
2496   match(RHS1, m_APInt(RHSC));
2497 
2498   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
2499   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
2500   // The original condition actually refers to the following two ranges:
2501   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
2502   // We can fold these two ranges if:
2503   // 1) C1 and C2 is unsigned greater than C3.
2504   // 2) The two ranges are separated.
2505   // 3) C1 ^ C2 is one-bit mask.
2506   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
2507   // This implies all values in the two ranges differ by exactly one bit.
2508   if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
2509       PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
2510       LHSC->getBitWidth() == RHSC->getBitWidth() && *LHSC == *RHSC) {
2511 
2512     Value *AddOpnd;
2513     const APInt *LAddC, *RAddC;
2514     if (match(LHS0, m_Add(m_Value(AddOpnd), m_APInt(LAddC))) &&
2515         match(RHS0, m_Add(m_Specific(AddOpnd), m_APInt(RAddC))) &&
2516         LAddC->ugt(*LHSC) && RAddC->ugt(*LHSC)) {
2517 
2518       APInt DiffC = *LAddC ^ *RAddC;
2519       if (DiffC.isPowerOf2()) {
2520         const APInt *MaxAddC = nullptr;
2521         if (LAddC->ult(*RAddC))
2522           MaxAddC = RAddC;
2523         else
2524           MaxAddC = LAddC;
2525 
2526         APInt RRangeLow = -*RAddC;
2527         APInt RRangeHigh = RRangeLow + *LHSC;
2528         APInt LRangeLow = -*LAddC;
2529         APInt LRangeHigh = LRangeLow + *LHSC;
2530         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
2531         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
2532         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
2533                                                    : RRangeLow - LRangeLow;
2534 
2535         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
2536             RangeDiff.ugt(*LHSC)) {
2537           Type *Ty = AddOpnd->getType();
2538           Value *MaskC = ConstantInt::get(Ty, ~DiffC);
2539 
2540           Value *NewAnd = Builder.CreateAnd(AddOpnd, MaskC);
2541           Value *NewAdd = Builder.CreateAdd(NewAnd,
2542                                             ConstantInt::get(Ty, *MaxAddC));
2543           return Builder.CreateICmp(LHS->getPredicate(), NewAdd,
2544                                     ConstantInt::get(Ty, *LHSC));
2545         }
2546       }
2547     }
2548   }
2549 
2550   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2551   if (predicatesFoldable(PredL, PredR)) {
2552     if (LHS0 == RHS1 && LHS1 == RHS0)
2553       LHS->swapOperands();
2554     if (LHS0 == RHS0 && LHS1 == RHS1) {
2555       unsigned Code =
2556           getICmpCode(LHS->getPredicate()) | getICmpCode(RHS->getPredicate());
2557       bool IsSigned = LHS->isSigned() || RHS->isSigned();
2558       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
2559     }
2560   }
2561 
2562   // handle (roughly):
2563   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
2564   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
2565     return V;
2566 
2567   if (LHS->hasOneUse() || RHS->hasOneUse()) {
2568     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2569     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
2570     Value *A = nullptr, *B = nullptr;
2571     if (PredL == ICmpInst::ICMP_EQ && match(LHS1, m_Zero())) {
2572       B = LHS0;
2573       if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS1)
2574         A = RHS0;
2575       else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
2576         A = RHS1;
2577     }
2578     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2579     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
2580     else if (PredR == ICmpInst::ICMP_EQ && match(RHS1, m_Zero())) {
2581       B = RHS0;
2582       if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS1)
2583         A = LHS0;
2584       else if (PredL == ICmpInst::ICMP_UGT && RHS0 == LHS0)
2585         A = LHS1;
2586     }
2587     if (A && B && B->getType()->isIntOrIntVectorTy())
2588       return Builder.CreateICmp(
2589           ICmpInst::ICMP_UGE,
2590           Builder.CreateAdd(B, Constant::getAllOnesValue(B->getType())), A);
2591   }
2592 
2593   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, Or, Builder, Q))
2594     return V;
2595   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, Or, Builder, Q))
2596     return V;
2597 
2598   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2599   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
2600     return V;
2601 
2602   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2603   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
2604     return V;
2605 
2606   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
2607     return V;
2608 
2609   if (Value *V = foldIsPowerOf2(LHS, RHS, false /* JoinedByAnd */, Builder))
2610     return V;
2611 
2612   if (Value *X =
2613           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/false, Q, Builder))
2614     return X;
2615   if (Value *X =
2616           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/false, Q, Builder))
2617     return X;
2618 
2619   if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/false))
2620     return X;
2621 
2622   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2623   // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs.
2624   if (PredL == ICmpInst::ICMP_NE && match(LHS1, m_ZeroInt()) &&
2625       PredR == ICmpInst::ICMP_NE && match(RHS1, m_ZeroInt()) &&
2626       LHS0->getType() == RHS0->getType()) {
2627     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
2628     return Builder.CreateICmp(PredL, NewOr,
2629                               Constant::getNullValue(NewOr->getType()));
2630   }
2631 
2632   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
2633   if (!LHSC || !RHSC)
2634     return nullptr;
2635 
2636   return foldAndOrOfICmpsUsingRanges(PredL, LHS0, *LHSC, PredR, RHS0, *RHSC,
2637                                      Builder, /* IsAnd */ false);
2638 }
2639 
2640 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2641 // here. We should standardize that construct where it is needed or choose some
2642 // other way to ensure that commutated variants of patterns are not missed.
2643 Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
2644   if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
2645                                 SQ.getWithInstruction(&I)))
2646     return replaceInstUsesWith(I, V);
2647 
2648   if (SimplifyAssociativeOrCommutative(I))
2649     return &I;
2650 
2651   if (Instruction *X = foldVectorBinop(I))
2652     return X;
2653 
2654   if (Instruction *Phi = foldBinopWithPhiOperands(I))
2655     return Phi;
2656 
2657   // See if we can simplify any instructions used by the instruction whose sole
2658   // purpose is to compute bits we don't care about.
2659   if (SimplifyDemandedInstructionBits(I))
2660     return &I;
2661 
2662   // Do this before using distributive laws to catch simple and/or/not patterns.
2663   if (Instruction *Xor = foldOrToXor(I, Builder))
2664     return Xor;
2665 
2666   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
2667     return X;
2668 
2669   // (A&B)|(A&C) -> A&(B|C) etc
2670   if (Value *V = SimplifyUsingDistributiveLaws(I))
2671     return replaceInstUsesWith(I, V);
2672 
2673   if (Value *V = SimplifyBSwap(I, Builder))
2674     return replaceInstUsesWith(I, V);
2675 
2676   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2677   Type *Ty = I.getType();
2678   if (Ty->isIntOrIntVectorTy(1)) {
2679     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
2680       if (auto *I =
2681               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
2682         return I;
2683     }
2684     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
2685       if (auto *I =
2686               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
2687         return I;
2688     }
2689   }
2690 
2691   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2692     return FoldedLogic;
2693 
2694   if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
2695                                                   /*MatchBitReversals*/ true))
2696     return BitOp;
2697 
2698   if (Instruction *Funnel = matchFunnelShift(I, *this))
2699     return Funnel;
2700 
2701   if (Instruction *Concat = matchOrConcat(I, Builder))
2702     return replaceInstUsesWith(I, Concat);
2703 
2704   Value *X, *Y;
2705   const APInt *CV;
2706   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
2707       !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
2708     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2709     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2710     Value *Or = Builder.CreateOr(X, Y);
2711     return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
2712   }
2713 
2714   // If the operands have no common bits set:
2715   // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
2716   if (match(&I,
2717             m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) &&
2718       haveNoCommonBitsSet(Op0, Op1, DL)) {
2719     Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
2720     return BinaryOperator::CreateMul(X, IncrementY);
2721   }
2722 
2723   // (A & C) | (B & D)
2724   Value *A, *B, *C, *D;
2725   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2726       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2727 
2728     // (A & C0) | (B & C1)
2729     const APInt *C0, *C1;
2730     if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
2731       Value *X;
2732       if (*C0 == ~*C1) {
2733         // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
2734         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
2735           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
2736         // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
2737         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
2738           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
2739 
2740         // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
2741         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
2742           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
2743         // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
2744         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
2745           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
2746       }
2747 
2748       if ((*C0 & *C1).isZero()) {
2749         // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
2750         // iff (C0 & C1) == 0 and (X & ~C0) == 0
2751         if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
2752             MaskedValueIsZero(X, ~*C0, 0, &I)) {
2753           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
2754           return BinaryOperator::CreateAnd(A, C01);
2755         }
2756         // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
2757         // iff (C0 & C1) == 0 and (X & ~C1) == 0
2758         if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
2759             MaskedValueIsZero(X, ~*C1, 0, &I)) {
2760           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
2761           return BinaryOperator::CreateAnd(B, C01);
2762         }
2763         // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
2764         // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
2765         const APInt *C2, *C3;
2766         if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
2767             match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
2768             (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
2769           Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
2770           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
2771           return BinaryOperator::CreateAnd(Or, C01);
2772         }
2773       }
2774     }
2775 
2776     // Don't try to form a select if it's unlikely that we'll get rid of at
2777     // least one of the operands. A select is generally more expensive than the
2778     // 'or' that it is replacing.
2779     if (Op0->hasOneUse() || Op1->hasOneUse()) {
2780       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2781       if (Value *V = matchSelectFromAndOr(A, C, B, D))
2782         return replaceInstUsesWith(I, V);
2783       if (Value *V = matchSelectFromAndOr(A, C, D, B))
2784         return replaceInstUsesWith(I, V);
2785       if (Value *V = matchSelectFromAndOr(C, A, B, D))
2786         return replaceInstUsesWith(I, V);
2787       if (Value *V = matchSelectFromAndOr(C, A, D, B))
2788         return replaceInstUsesWith(I, V);
2789       if (Value *V = matchSelectFromAndOr(B, D, A, C))
2790         return replaceInstUsesWith(I, V);
2791       if (Value *V = matchSelectFromAndOr(B, D, C, A))
2792         return replaceInstUsesWith(I, V);
2793       if (Value *V = matchSelectFromAndOr(D, B, A, C))
2794         return replaceInstUsesWith(I, V);
2795       if (Value *V = matchSelectFromAndOr(D, B, C, A))
2796         return replaceInstUsesWith(I, V);
2797     }
2798   }
2799 
2800   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2801   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2802     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2803       return BinaryOperator::CreateOr(Op0, C);
2804 
2805   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2806   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2807     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2808       return BinaryOperator::CreateOr(Op1, C);
2809 
2810   // ((B | C) & A) | B -> B | (A & C)
2811   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2812     return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
2813 
2814   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2815     return DeMorgan;
2816 
2817   // Canonicalize xor to the RHS.
2818   bool SwappedForXor = false;
2819   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2820     std::swap(Op0, Op1);
2821     SwappedForXor = true;
2822   }
2823 
2824   // A | ( A ^ B) -> A |  B
2825   // A | (~A ^ B) -> A | ~B
2826   // (A & B) | (A ^ B)
2827   // ~A | (A ^ B) -> ~(A & B)
2828   // The swap above should always make Op0 the 'not' for the last case.
2829   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2830     if (Op0 == A || Op0 == B)
2831       return BinaryOperator::CreateOr(A, B);
2832 
2833     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2834         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2835       return BinaryOperator::CreateOr(A, B);
2836 
2837     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
2838         (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
2839       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
2840 
2841     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2842       Value *Not = Builder.CreateNot(B, B->getName() + ".not");
2843       return BinaryOperator::CreateOr(Not, Op0);
2844     }
2845     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2846       Value *Not = Builder.CreateNot(A, A->getName() + ".not");
2847       return BinaryOperator::CreateOr(Not, Op0);
2848     }
2849   }
2850 
2851   // A | ~(A | B) -> A | ~B
2852   // A | ~(A ^ B) -> A | ~B
2853   if (match(Op1, m_Not(m_Value(A))))
2854     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2855       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2856           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2857                                B->getOpcode() == Instruction::Xor)) {
2858         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2859                                                  B->getOperand(0);
2860         Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
2861         return BinaryOperator::CreateOr(Not, Op0);
2862       }
2863 
2864   if (SwappedForXor)
2865     std::swap(Op0, Op1);
2866 
2867   {
2868     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2869     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2870     if (LHS && RHS)
2871       if (Value *Res = foldOrOfICmps(LHS, RHS, I))
2872         return replaceInstUsesWith(I, Res);
2873 
2874     // TODO: Make this recursive; it's a little tricky because an arbitrary
2875     // number of 'or' instructions might have to be created.
2876     Value *X, *Y;
2877     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2878       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2879         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2880           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2881       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2882         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2883           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2884     }
2885     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2886       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2887         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2888           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2889       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2890         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2891           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2892     }
2893   }
2894 
2895   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2896     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2897       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
2898         return replaceInstUsesWith(I, Res);
2899 
2900   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2901     return FoldedFCmps;
2902 
2903   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2904     return CastedOr;
2905 
2906   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
2907     return Sel;
2908 
2909   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2910   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
2911   //       with binop identity constant. But creating a select with non-constant
2912   //       arm may not be reversible due to poison semantics. Is that a good
2913   //       canonicalization?
2914   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2915       A->getType()->isIntOrIntVectorTy(1))
2916     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1);
2917   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2918       A->getType()->isIntOrIntVectorTy(1))
2919     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0);
2920 
2921   // Note: If we've gotten to the point of visiting the outer OR, then the
2922   // inner one couldn't be simplified.  If it was a constant, then it won't
2923   // be simplified by a later pass either, so we try swapping the inner/outer
2924   // ORs in the hopes that we'll be able to simplify it this way.
2925   // (X|C) | V --> (X|V) | C
2926   ConstantInt *CI;
2927   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
2928       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
2929     Value *Inner = Builder.CreateOr(A, Op1);
2930     Inner->takeName(Op0);
2931     return BinaryOperator::CreateOr(Inner, CI);
2932   }
2933 
2934   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2935   // Since this OR statement hasn't been optimized further yet, we hope
2936   // that this transformation will allow the new ORs to be optimized.
2937   {
2938     Value *X = nullptr, *Y = nullptr;
2939     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2940         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2941         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2942       Value *orTrue = Builder.CreateOr(A, C);
2943       Value *orFalse = Builder.CreateOr(B, D);
2944       return SelectInst::Create(X, orTrue, orFalse);
2945     }
2946   }
2947 
2948   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
2949   {
2950     Value *X, *Y;
2951     if (match(&I, m_c_Or(m_OneUse(m_AShr(
2952                              m_NSWSub(m_Value(Y), m_Value(X)),
2953                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
2954                          m_Deferred(X)))) {
2955       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
2956       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
2957       return SelectInst::Create(NewICmpInst, AllOnes, X);
2958     }
2959   }
2960 
2961   if (Instruction *V =
2962           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2963     return V;
2964 
2965   CmpInst::Predicate Pred;
2966   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
2967   // Check if the OR weakens the overflow condition for umul.with.overflow by
2968   // treating any non-zero result as overflow. In that case, we overflow if both
2969   // umul.with.overflow operands are != 0, as in that case the result can only
2970   // be 0, iff the multiplication overflows.
2971   if (match(&I,
2972             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
2973                                 m_Value(Ov)),
2974                    m_CombineAnd(m_ICmp(Pred,
2975                                        m_CombineAnd(m_ExtractValue<0>(
2976                                                         m_Deferred(UMulWithOv)),
2977                                                     m_Value(Mul)),
2978                                        m_ZeroInt()),
2979                                 m_Value(MulIsNotZero)))) &&
2980       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
2981       Pred == CmpInst::ICMP_NE) {
2982     Value *A, *B;
2983     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
2984                               m_Value(A), m_Value(B)))) {
2985       Value *NotNullA = Builder.CreateIsNotNull(A);
2986       Value *NotNullB = Builder.CreateIsNotNull(B);
2987       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
2988     }
2989   }
2990 
2991   // (~x) | y  -->  ~(x & (~y))  iff that gets rid of inversions
2992   if (sinkNotIntoOtherHandOfAndOrOr(I))
2993     return &I;
2994 
2995   // Improve "get low bit mask up to and including bit X" pattern:
2996   //   (1 << X) | ((1 << X) + -1)  -->  -1 l>> (bitwidth(x) - 1 - X)
2997   if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
2998                        m_Shl(m_One(), m_Deferred(X)))) &&
2999       match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
3000     Value *Sub = Builder.CreateSub(
3001         ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
3002     return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
3003   }
3004 
3005   // An or recurrence w/loop invariant step is equivelent to (or start, step)
3006   PHINode *PN = nullptr;
3007   Value *Start = nullptr, *Step = nullptr;
3008   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
3009     return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
3010 
3011   return nullptr;
3012 }
3013 
3014 /// A ^ B can be specified using other logic ops in a variety of patterns. We
3015 /// can fold these early and efficiently by morphing an existing instruction.
3016 static Instruction *foldXorToXor(BinaryOperator &I,
3017                                  InstCombiner::BuilderTy &Builder) {
3018   assert(I.getOpcode() == Instruction::Xor);
3019   Value *Op0 = I.getOperand(0);
3020   Value *Op1 = I.getOperand(1);
3021   Value *A, *B;
3022 
3023   // There are 4 commuted variants for each of the basic patterns.
3024 
3025   // (A & B) ^ (A | B) -> A ^ B
3026   // (A & B) ^ (B | A) -> A ^ B
3027   // (A | B) ^ (A & B) -> A ^ B
3028   // (A | B) ^ (B & A) -> A ^ B
3029   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
3030                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
3031     return BinaryOperator::CreateXor(A, B);
3032 
3033   // (A | ~B) ^ (~A | B) -> A ^ B
3034   // (~B | A) ^ (~A | B) -> A ^ B
3035   // (~A | B) ^ (A | ~B) -> A ^ B
3036   // (B | ~A) ^ (A | ~B) -> A ^ B
3037   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
3038                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
3039     return BinaryOperator::CreateXor(A, B);
3040 
3041   // (A & ~B) ^ (~A & B) -> A ^ B
3042   // (~B & A) ^ (~A & B) -> A ^ B
3043   // (~A & B) ^ (A & ~B) -> A ^ B
3044   // (B & ~A) ^ (A & ~B) -> A ^ B
3045   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
3046                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
3047     return BinaryOperator::CreateXor(A, B);
3048 
3049   // For the remaining cases we need to get rid of one of the operands.
3050   if (!Op0->hasOneUse() && !Op1->hasOneUse())
3051     return nullptr;
3052 
3053   // (A | B) ^ ~(A & B) -> ~(A ^ B)
3054   // (A | B) ^ ~(B & A) -> ~(A ^ B)
3055   // (A & B) ^ ~(A | B) -> ~(A ^ B)
3056   // (A & B) ^ ~(B | A) -> ~(A ^ B)
3057   // Complexity sorting ensures the not will be on the right side.
3058   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
3059        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
3060       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3061        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
3062     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
3063 
3064   return nullptr;
3065 }
3066 
3067 Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3068                                         BinaryOperator &I) {
3069   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
3070          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
3071 
3072   if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
3073     if (LHS->getOperand(0) == RHS->getOperand(1) &&
3074         LHS->getOperand(1) == RHS->getOperand(0))
3075       LHS->swapOperands();
3076     if (LHS->getOperand(0) == RHS->getOperand(0) &&
3077         LHS->getOperand(1) == RHS->getOperand(1)) {
3078       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3079       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
3080       unsigned Code =
3081           getICmpCode(LHS->getPredicate()) ^ getICmpCode(RHS->getPredicate());
3082       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3083       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
3084     }
3085   }
3086 
3087   // TODO: This can be generalized to compares of non-signbits using
3088   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
3089   // foldLogOpOfMaskedICmps().
3090   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3091   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
3092   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
3093   if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
3094       LHS0->getType() == RHS0->getType() &&
3095       LHS0->getType()->isIntOrIntVectorTy()) {
3096     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
3097     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
3098     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
3099          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
3100         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
3101          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
3102       Value *Zero = ConstantInt::getNullValue(LHS0->getType());
3103       return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
3104     }
3105     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
3106     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
3107     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
3108          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
3109         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
3110          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
3111       Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
3112       return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
3113     }
3114   }
3115 
3116   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
3117   // into those logic ops. That is, try to turn this into an and-of-icmps
3118   // because we have many folds for that pattern.
3119   //
3120   // This is based on a truth table definition of xor:
3121   // X ^ Y --> (X | Y) & !(X & Y)
3122   if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
3123     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
3124     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
3125     if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
3126       // TODO: Independently handle cases where the 'and' side is a constant.
3127       ICmpInst *X = nullptr, *Y = nullptr;
3128       if (OrICmp == LHS && AndICmp == RHS) {
3129         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
3130         X = LHS;
3131         Y = RHS;
3132       }
3133       if (OrICmp == RHS && AndICmp == LHS) {
3134         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
3135         X = RHS;
3136         Y = LHS;
3137       }
3138       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
3139         // Invert the predicate of 'Y', thus inverting its output.
3140         Y->setPredicate(Y->getInversePredicate());
3141         // So, are there other uses of Y?
3142         if (!Y->hasOneUse()) {
3143           // We need to adapt other uses of Y though. Get a value that matches
3144           // the original value of Y before inversion. While this increases
3145           // immediate instruction count, we have just ensured that all the
3146           // users are freely-invertible, so that 'not' *will* get folded away.
3147           BuilderTy::InsertPointGuard Guard(Builder);
3148           // Set insertion point to right after the Y.
3149           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
3150           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3151           // Replace all uses of Y (excluding the one in NotY!) with NotY.
3152           Worklist.pushUsersToWorkList(*Y);
3153           Y->replaceUsesWithIf(NotY,
3154                                [NotY](Use &U) { return U.getUser() != NotY; });
3155         }
3156         // All done.
3157         return Builder.CreateAnd(LHS, RHS);
3158       }
3159     }
3160   }
3161 
3162   return nullptr;
3163 }
3164 
3165 /// If we have a masked merge, in the canonical form of:
3166 /// (assuming that A only has one use.)
3167 ///   |        A  |  |B|
3168 ///   ((x ^ y) & M) ^ y
3169 ///    |  D  |
3170 /// * If M is inverted:
3171 ///      |  D  |
3172 ///     ((x ^ y) & ~M) ^ y
3173 ///   We can canonicalize by swapping the final xor operand
3174 ///   to eliminate the 'not' of the mask.
3175 ///     ((x ^ y) & M) ^ x
3176 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
3177 ///   because that shortens the dependency chain and improves analysis:
3178 ///     (x & M) | (y & ~M)
3179 static Instruction *visitMaskedMerge(BinaryOperator &I,
3180                                      InstCombiner::BuilderTy &Builder) {
3181   Value *B, *X, *D;
3182   Value *M;
3183   if (!match(&I, m_c_Xor(m_Value(B),
3184                          m_OneUse(m_c_And(
3185                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
3186                                           m_Value(D)),
3187                              m_Value(M))))))
3188     return nullptr;
3189 
3190   Value *NotM;
3191   if (match(M, m_Not(m_Value(NotM)))) {
3192     // De-invert the mask and swap the value in B part.
3193     Value *NewA = Builder.CreateAnd(D, NotM);
3194     return BinaryOperator::CreateXor(NewA, X);
3195   }
3196 
3197   Constant *C;
3198   if (D->hasOneUse() && match(M, m_Constant(C))) {
3199     // Propagating undef is unsafe. Clamp undef elements to -1.
3200     Type *EltTy = C->getType()->getScalarType();
3201     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3202     // Unfold.
3203     Value *LHS = Builder.CreateAnd(X, C);
3204     Value *NotC = Builder.CreateNot(C);
3205     Value *RHS = Builder.CreateAnd(B, NotC);
3206     return BinaryOperator::CreateOr(LHS, RHS);
3207   }
3208 
3209   return nullptr;
3210 }
3211 
3212 // Transform
3213 //   ~(x ^ y)
3214 // into:
3215 //   (~x) ^ y
3216 // or into
3217 //   x ^ (~y)
3218 static Instruction *sinkNotIntoXor(BinaryOperator &I,
3219                                    InstCombiner::BuilderTy &Builder) {
3220   Value *X, *Y;
3221   // FIXME: one-use check is not needed in general, but currently we are unable
3222   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
3223   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
3224     return nullptr;
3225 
3226   // We only want to do the transform if it is free to do.
3227   if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
3228     // Ok, good.
3229   } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
3230     std::swap(X, Y);
3231   } else
3232     return nullptr;
3233 
3234   Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
3235   return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
3236 }
3237 
3238 /// Canonicalize a shifty way to code absolute value to the more common pattern
3239 /// that uses negation and select.
3240 static Instruction *canonicalizeAbs(BinaryOperator &Xor,
3241                                     InstCombiner::BuilderTy &Builder) {
3242   assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
3243 
3244   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
3245   // We're relying on the fact that we only do this transform when the shift has
3246   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
3247   // instructions).
3248   Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
3249   if (Op0->hasNUses(2))
3250     std::swap(Op0, Op1);
3251 
3252   Type *Ty = Xor.getType();
3253   Value *A;
3254   const APInt *ShAmt;
3255   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
3256       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
3257       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
3258     // Op1 = ashr i32 A, 31   ; smear the sign bit
3259     // xor (add A, Op1), Op1  ; add -1 and flip bits if negative
3260     // --> (A < 0) ? -A : A
3261     Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
3262     // Copy the nuw/nsw flags from the add to the negate.
3263     auto *Add = cast<BinaryOperator>(Op0);
3264     Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
3265                                    Add->hasNoSignedWrap());
3266     return SelectInst::Create(Cmp, Neg, A);
3267   }
3268   return nullptr;
3269 }
3270 
3271 // Transform
3272 //   z = (~x) &/| y
3273 // into:
3274 //   z = ~(x |/& (~y))
3275 // iff y is free to invert and all uses of z can be freely updated.
3276 bool InstCombinerImpl::sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I) {
3277   Instruction::BinaryOps NewOpc;
3278   switch (I.getOpcode()) {
3279   case Instruction::And:
3280     NewOpc = Instruction::Or;
3281     break;
3282   case Instruction::Or:
3283     NewOpc = Instruction::And;
3284     break;
3285   default:
3286     return false;
3287   };
3288 
3289   Value *X, *Y;
3290   if (!match(&I, m_c_BinOp(m_Not(m_Value(X)), m_Value(Y))))
3291     return false;
3292 
3293   // Will we be able to fold the `not` into Y eventually?
3294   if (!InstCombiner::isFreeToInvert(Y, Y->hasOneUse()))
3295     return false;
3296 
3297   // And can our users be adapted?
3298   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
3299     return false;
3300 
3301   Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3302   Value *NewBinOp =
3303       BinaryOperator::Create(NewOpc, X, NotY, I.getName() + ".not");
3304   Builder.Insert(NewBinOp);
3305   replaceInstUsesWith(I, NewBinOp);
3306   // We can not just create an outer `not`, it will most likely be immediately
3307   // folded back, reconstructing our initial pattern, and causing an
3308   // infinite combine loop, so immediately manually fold it away.
3309   freelyInvertAllUsersOf(NewBinOp);
3310   return true;
3311 }
3312 
3313 Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
3314   Value *NotOp;
3315   if (!match(&I, m_Not(m_Value(NotOp))))
3316     return nullptr;
3317 
3318   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
3319   // We must eliminate the and/or (one-use) for these transforms to not increase
3320   // the instruction count.
3321   //
3322   // ~(~X & Y) --> (X | ~Y)
3323   // ~(Y & ~X) --> (X | ~Y)
3324   //
3325   // Note: The logical matches do not check for the commuted patterns because
3326   //       those are handled via SimplifySelectsFeedingBinaryOp().
3327   Type *Ty = I.getType();
3328   Value *X, *Y;
3329   if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
3330     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3331     return BinaryOperator::CreateOr(X, NotY);
3332   }
3333   if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
3334     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3335     return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
3336   }
3337 
3338   // ~(~X | Y) --> (X & ~Y)
3339   // ~(Y | ~X) --> (X & ~Y)
3340   if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
3341     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3342     return BinaryOperator::CreateAnd(X, NotY);
3343   }
3344   if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
3345     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3346     return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
3347   }
3348 
3349   // Is this a 'not' (~) fed by a binary operator?
3350   BinaryOperator *NotVal;
3351   if (match(NotOp, m_BinOp(NotVal))) {
3352     if (NotVal->getOpcode() == Instruction::And ||
3353         NotVal->getOpcode() == Instruction::Or) {
3354       // Apply DeMorgan's Law when inverts are free:
3355       // ~(X & Y) --> (~X | ~Y)
3356       // ~(X | Y) --> (~X & ~Y)
3357       if (isFreeToInvert(NotVal->getOperand(0),
3358                          NotVal->getOperand(0)->hasOneUse()) &&
3359           isFreeToInvert(NotVal->getOperand(1),
3360                          NotVal->getOperand(1)->hasOneUse())) {
3361         Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
3362         Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
3363         if (NotVal->getOpcode() == Instruction::And)
3364           return BinaryOperator::CreateOr(NotX, NotY);
3365         return BinaryOperator::CreateAnd(NotX, NotY);
3366       }
3367     }
3368 
3369     // ~((-X) | Y) --> (X - 1) & (~Y)
3370     if (match(NotVal,
3371               m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
3372       Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
3373       Value *NotY = Builder.CreateNot(Y);
3374       return BinaryOperator::CreateAnd(DecX, NotY);
3375     }
3376 
3377     // ~(~X >>s Y) --> (X >>s Y)
3378     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
3379       return BinaryOperator::CreateAShr(X, Y);
3380 
3381     // If we are inverting a right-shifted constant, we may be able to eliminate
3382     // the 'not' by inverting the constant and using the opposite shift type.
3383     // Canonicalization rules ensure that only a negative constant uses 'ashr',
3384     // but we must check that in case that transform has not fired yet.
3385 
3386     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
3387     Constant *C;
3388     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
3389         match(C, m_Negative())) {
3390       // We matched a negative constant, so propagating undef is unsafe.
3391       // Clamp undef elements to -1.
3392       Type *EltTy = Ty->getScalarType();
3393       C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3394       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
3395     }
3396 
3397     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
3398     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
3399         match(C, m_NonNegative())) {
3400       // We matched a non-negative constant, so propagating undef is unsafe.
3401       // Clamp undef elements to 0.
3402       Type *EltTy = Ty->getScalarType();
3403       C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
3404       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
3405     }
3406 
3407     // ~(X + C) --> ~C - X
3408     if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
3409       return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
3410 
3411     // ~(X - Y) --> ~X + Y
3412     // FIXME: is it really beneficial to sink the `not` here?
3413     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
3414       if (isa<Constant>(X) || NotVal->hasOneUse())
3415         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
3416 
3417     // ~(~X + Y) --> X - Y
3418     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
3419       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
3420                                                    NotVal);
3421   }
3422 
3423   // not (cmp A, B) = !cmp A, B
3424   CmpInst::Predicate Pred;
3425   if (match(NotOp, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
3426     cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
3427     return replaceInstUsesWith(I, NotOp);
3428   }
3429 
3430   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3431   // ~min(~X, ~Y) --> max(X, Y)
3432   // ~max(~X, Y) --> min(X, ~Y)
3433   auto *II = dyn_cast<IntrinsicInst>(NotOp);
3434   if (II && II->hasOneUse()) {
3435     if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
3436         isFreeToInvert(X, X->hasOneUse()) &&
3437         isFreeToInvert(Y, Y->hasOneUse())) {
3438       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
3439       Value *NotX = Builder.CreateNot(X);
3440       Value *NotY = Builder.CreateNot(Y);
3441       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
3442       return replaceInstUsesWith(I, InvMaxMin);
3443     }
3444     if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
3445       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
3446       Value *NotY = Builder.CreateNot(Y);
3447       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
3448       return replaceInstUsesWith(I, InvMaxMin);
3449     }
3450   }
3451 
3452   if (NotOp->hasOneUse()) {
3453     // Pull 'not' into operands of select if both operands are one-use compares
3454     // or one is one-use compare and the other one is a constant.
3455     // Inverting the predicates eliminates the 'not' operation.
3456     // Example:
3457     //   not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
3458     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
3459     //   not (select ?, (cmp TPred, ?, ?), true -->
3460     //     select ?, (cmp InvTPred, ?, ?), false
3461     if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
3462       Value *TV = Sel->getTrueValue();
3463       Value *FV = Sel->getFalseValue();
3464       auto *CmpT = dyn_cast<CmpInst>(TV);
3465       auto *CmpF = dyn_cast<CmpInst>(FV);
3466       bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
3467       bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
3468       if (InvertibleT && InvertibleF) {
3469         if (CmpT)
3470           CmpT->setPredicate(CmpT->getInversePredicate());
3471         else
3472           Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
3473         if (CmpF)
3474           CmpF->setPredicate(CmpF->getInversePredicate());
3475         else
3476           Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
3477         return replaceInstUsesWith(I, Sel);
3478       }
3479     }
3480   }
3481 
3482   if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
3483     return NewXor;
3484 
3485   return nullptr;
3486 }
3487 
3488 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
3489 // here. We should standardize that construct where it is needed or choose some
3490 // other way to ensure that commutated variants of patterns are not missed.
3491 Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
3492   if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
3493                                  SQ.getWithInstruction(&I)))
3494     return replaceInstUsesWith(I, V);
3495 
3496   if (SimplifyAssociativeOrCommutative(I))
3497     return &I;
3498 
3499   if (Instruction *X = foldVectorBinop(I))
3500     return X;
3501 
3502   if (Instruction *Phi = foldBinopWithPhiOperands(I))
3503     return Phi;
3504 
3505   if (Instruction *NewXor = foldXorToXor(I, Builder))
3506     return NewXor;
3507 
3508   // (A&B)^(A&C) -> A&(B^C) etc
3509   if (Value *V = SimplifyUsingDistributiveLaws(I))
3510     return replaceInstUsesWith(I, V);
3511 
3512   // See if we can simplify any instructions used by the instruction whose sole
3513   // purpose is to compute bits we don't care about.
3514   if (SimplifyDemandedInstructionBits(I))
3515     return &I;
3516 
3517   if (Value *V = SimplifyBSwap(I, Builder))
3518     return replaceInstUsesWith(I, V);
3519 
3520   if (Instruction *R = foldNot(I))
3521     return R;
3522 
3523   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
3524   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
3525   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
3526   // have already taken care of those cases.
3527   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3528   Value *M;
3529   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
3530                         m_c_And(m_Deferred(M), m_Value()))))
3531     return BinaryOperator::CreateOr(Op0, Op1);
3532 
3533   if (Instruction *Xor = visitMaskedMerge(I, Builder))
3534     return Xor;
3535 
3536   Value *X, *Y;
3537   Constant *C1;
3538   if (match(Op1, m_Constant(C1))) {
3539     // Use DeMorgan and reassociation to eliminate a 'not' op.
3540     Constant *C2;
3541     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
3542       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
3543       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
3544       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
3545     }
3546     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
3547       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
3548       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
3549       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
3550     }
3551 
3552     // Convert xor ([trunc] (ashr X, BW-1)), C =>
3553     //   select(X >s -1, C, ~C)
3554     // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
3555     // constant depending on whether this input is less than 0.
3556     const APInt *CA;
3557     if (match(Op0, m_OneUse(m_TruncOrSelf(
3558                        m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
3559         *CA == X->getType()->getScalarSizeInBits() - 1 &&
3560         !match(C1, m_AllOnes())) {
3561       assert(!C1->isZeroValue() && "Unexpected xor with 0");
3562       Value *ICmp =
3563           Builder.CreateICmpSGT(X, Constant::getAllOnesValue(X->getType()));
3564       return SelectInst::Create(ICmp, Op1, Builder.CreateNot(Op1));
3565     }
3566   }
3567 
3568   Type *Ty = I.getType();
3569   {
3570     const APInt *RHSC;
3571     if (match(Op1, m_APInt(RHSC))) {
3572       Value *X;
3573       const APInt *C;
3574       // (C - X) ^ signmaskC --> (C + signmaskC) - X
3575       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
3576         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
3577 
3578       // (X + C) ^ signmaskC --> X + (C + signmaskC)
3579       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
3580         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
3581 
3582       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
3583       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
3584           MaskedValueIsZero(X, *C, 0, &I))
3585         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
3586 
3587       // If RHSC is inverting the remaining bits of shifted X,
3588       // canonicalize to a 'not' before the shift to help SCEV and codegen:
3589       // (X << C) ^ RHSC --> ~X << C
3590       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
3591           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
3592         Value *NotX = Builder.CreateNot(X);
3593         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
3594       }
3595       // (X >>u C) ^ RHSC --> ~X >>u C
3596       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
3597           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
3598         Value *NotX = Builder.CreateNot(X);
3599         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
3600       }
3601       // TODO: We could handle 'ashr' here as well. That would be matching
3602       //       a 'not' op and moving it before the shift. Doing that requires
3603       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
3604     }
3605   }
3606 
3607   // FIXME: This should not be limited to scalar (pull into APInt match above).
3608   {
3609     Value *X;
3610     ConstantInt *C1, *C2, *C3;
3611     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
3612     if (match(Op1, m_ConstantInt(C3)) &&
3613         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
3614                           m_ConstantInt(C2))) &&
3615         Op0->hasOneUse()) {
3616       // fold (C1 >> C2) ^ C3
3617       APInt FoldConst = C1->getValue().lshr(C2->getValue());
3618       FoldConst ^= C3->getValue();
3619       // Prepare the two operands.
3620       auto *Opnd0 = Builder.CreateLShr(X, C2);
3621       Opnd0->takeName(Op0);
3622       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
3623     }
3624   }
3625 
3626   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
3627     return FoldedLogic;
3628 
3629   // Y ^ (X | Y) --> X & ~Y
3630   // Y ^ (Y | X) --> X & ~Y
3631   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
3632     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
3633   // (X | Y) ^ Y --> X & ~Y
3634   // (Y | X) ^ Y --> X & ~Y
3635   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
3636     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
3637 
3638   // Y ^ (X & Y) --> ~X & Y
3639   // Y ^ (Y & X) --> ~X & Y
3640   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
3641     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
3642   // (X & Y) ^ Y --> ~X & Y
3643   // (Y & X) ^ Y --> ~X & Y
3644   // Canonical form is (X & C) ^ C; don't touch that.
3645   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
3646   //       be fixed to prefer that (otherwise we get infinite looping).
3647   if (!match(Op1, m_Constant()) &&
3648       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
3649     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
3650 
3651   Value *A, *B, *C;
3652   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
3653   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3654                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
3655       return BinaryOperator::CreateXor(
3656           Builder.CreateAnd(Builder.CreateNot(A), C), B);
3657 
3658   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
3659   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3660                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
3661       return BinaryOperator::CreateXor(
3662           Builder.CreateAnd(Builder.CreateNot(B), C), A);
3663 
3664   // (A & B) ^ (A ^ B) -> (A | B)
3665   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3666       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
3667     return BinaryOperator::CreateOr(A, B);
3668   // (A ^ B) ^ (A & B) -> (A | B)
3669   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3670       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
3671     return BinaryOperator::CreateOr(A, B);
3672 
3673   // (A & ~B) ^ ~A -> ~(A & B)
3674   // (~B & A) ^ ~A -> ~(A & B)
3675   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
3676       match(Op1, m_Not(m_Specific(A))))
3677     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3678 
3679   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
3680   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
3681     return BinaryOperator::CreateOr(A, B);
3682 
3683   // (~A | B) ^ A --> ~(A & B)
3684   if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
3685     return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
3686 
3687   // A ^ (~A | B) --> ~(A & B)
3688   if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
3689     return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
3690 
3691   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
3692   // TODO: Loosen one-use restriction if common operand is a constant.
3693   Value *D;
3694   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
3695       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
3696     if (B == C || B == D)
3697       std::swap(A, B);
3698     if (A == C)
3699       std::swap(C, D);
3700     if (A == D) {
3701       Value *NotA = Builder.CreateNot(A);
3702       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
3703     }
3704   }
3705 
3706   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3707     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
3708       if (Value *V = foldXorOfICmps(LHS, RHS, I))
3709         return replaceInstUsesWith(I, V);
3710 
3711   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
3712     return CastedXor;
3713 
3714   if (Instruction *Abs = canonicalizeAbs(I, Builder))
3715     return Abs;
3716 
3717   // Otherwise, if all else failed, try to hoist the xor-by-constant:
3718   //   (X ^ C) ^ Y --> (X ^ Y) ^ C
3719   // Just like we do in other places, we completely avoid the fold
3720   // for constantexprs, at least to avoid endless combine loop.
3721   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
3722                                                     m_Unless(m_ConstantExpr())),
3723                                        m_ImmConstant(C1))),
3724                         m_Value(Y))))
3725     return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
3726 
3727   return nullptr;
3728 }
3729