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/ADT/SmallBitVector.h"
15#include "llvm/Analysis/CmpInstAnalysis.h"
16#include "llvm/Analysis/FloatingPointPredicateUtils.h"
17#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/IR/ConstantRange.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/PatternMatch.h"
23#include "llvm/IR/ProfDataUtils.h"
24#include "llvm/Transforms/InstCombine/InstCombiner.h"
25#include "llvm/Transforms/Utils/Local.h"
26
27using namespace llvm;
28using namespace PatternMatch;
29
30#define DEBUG_TYPE "instcombine"
31
32namespace llvm {
33extern cl::opt<bool> ProfcheckDisableMetadataFixes;
34}
35
36/// This is the complement of getICmpCode, which turns an opcode and two
37/// operands into either a constant true or false, or a brand new ICmp
38/// instruction. The sign is passed in to determine which kind of predicate to
39/// use in the new icmp instruction.
40static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
41 InstCombiner::BuilderTy &Builder) {
42 ICmpInst::Predicate NewPred;
43 if (Constant *TorF = getPredForICmpCode(Code, Sign, OpTy: LHS->getType(), Pred&: NewPred))
44 return TorF;
45 return Builder.CreateICmp(P: NewPred, LHS, RHS);
46}
47
48/// This is the complement of getFCmpCode, which turns an opcode and two
49/// operands into either a FCmp instruction, or a true/false constant.
50static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
51 InstCombiner::BuilderTy &Builder, FMFSource FMF) {
52 FCmpInst::Predicate NewPred;
53 if (Constant *TorF = getPredForFCmpCode(Code, OpTy: LHS->getType(), Pred&: NewPred))
54 return TorF;
55 return Builder.CreateFCmpFMF(P: NewPred, LHS, RHS, FMFSource: FMF);
56}
57
58/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
59/// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
60/// whether to treat V, Lo, and Hi as signed or not.
61Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
62 const APInt &Hi, bool isSigned,
63 bool Inside) {
64 assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
65 "Lo is not < Hi in range emission code!");
66
67 Type *Ty = V->getType();
68
69 // V >= Min && V < Hi --> V < Hi
70 // V < Min || V >= Hi --> V >= Hi
71 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
72 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
73 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
74 return Builder.CreateICmp(P: Pred, LHS: V, RHS: ConstantInt::get(Ty, V: Hi));
75 }
76
77 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
78 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
79 Value *VMinusLo =
80 Builder.CreateSub(LHS: V, RHS: ConstantInt::get(Ty, V: Lo), Name: V->getName() + ".off");
81 Constant *HiMinusLo = ConstantInt::get(Ty, V: Hi - Lo);
82 return Builder.CreateICmp(P: Pred, LHS: VMinusLo, RHS: HiMinusLo);
83}
84
85/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
86/// that can be simplified.
87/// One of A and B is considered the mask. The other is the value. This is
88/// described as the "AMask" or "BMask" part of the enum. If the enum contains
89/// only "Mask", then both A and B can be considered masks. If A is the mask,
90/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
91/// If both A and C are constants, this proof is also easy.
92/// For the following explanations, we assume that A is the mask.
93///
94/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
95/// bits of A are set in B.
96/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
97///
98/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
99/// bits of A are cleared in B.
100/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
101///
102/// "Mixed" declares that (A & B) == C and C might or might not contain any
103/// number of one bits and zero bits.
104/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
105///
106/// "Not" means that in above descriptions "==" should be replaced by "!=".
107/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
108///
109/// If the mask A contains a single bit, then the following is equivalent:
110/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
111/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
112enum MaskedICmpType {
113 AMask_AllOnes = 1,
114 AMask_NotAllOnes = 2,
115 BMask_AllOnes = 4,
116 BMask_NotAllOnes = 8,
117 Mask_AllZeros = 16,
118 Mask_NotAllZeros = 32,
119 AMask_Mixed = 64,
120 AMask_NotMixed = 128,
121 BMask_Mixed = 256,
122 BMask_NotMixed = 512
123};
124
125/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
126/// satisfies.
127static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
128 ICmpInst::Predicate Pred) {
129 const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
130 match(V: A, P: m_APInt(Res&: ConstA));
131 match(V: B, P: m_APInt(Res&: ConstB));
132 match(V: C, P: m_APInt(Res&: ConstC));
133 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
134 bool IsAPow2 = ConstA && ConstA->isPowerOf2();
135 bool IsBPow2 = ConstB && ConstB->isPowerOf2();
136 unsigned MaskVal = 0;
137 if (ConstC && ConstC->isZero()) {
138 // if C is zero, then both A and B qualify as mask
139 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
140 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
141 if (IsAPow2)
142 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
143 : (AMask_AllOnes | AMask_Mixed));
144 if (IsBPow2)
145 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
146 : (BMask_AllOnes | BMask_Mixed));
147 return MaskVal;
148 }
149
150 if (A == C) {
151 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
152 : (AMask_NotAllOnes | AMask_NotMixed));
153 if (IsAPow2)
154 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
155 : (Mask_AllZeros | AMask_Mixed));
156 } else if (ConstA && ConstC && ConstC->isSubsetOf(RHS: *ConstA)) {
157 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
158 }
159
160 if (B == C) {
161 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
162 : (BMask_NotAllOnes | BMask_NotMixed));
163 if (IsBPow2)
164 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
165 : (Mask_AllZeros | BMask_Mixed));
166 } else if (ConstB && ConstC && ConstC->isSubsetOf(RHS: *ConstB)) {
167 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
168 }
169
170 return MaskVal;
171}
172
173/// Convert an analysis of a masked ICmp into its equivalent if all boolean
174/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
175/// is adjacent to the corresponding normal flag (recording ==), this just
176/// involves swapping those bits over.
177static unsigned conjugateICmpMask(unsigned Mask) {
178 unsigned NewMask;
179 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
180 AMask_Mixed | BMask_Mixed))
181 << 1;
182
183 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
184 AMask_NotMixed | BMask_NotMixed))
185 >> 1;
186
187 return NewMask;
188}
189
190// Adapts the external decomposeBitTest for local use.
191static bool decomposeBitTest(Value *Cond, CmpInst::Predicate &Pred, Value *&X,
192 Value *&Y, Value *&Z) {
193 auto Res =
194 llvm::decomposeBitTest(Cond, /*LookThroughTrunc=*/true,
195 /*AllowNonZeroC=*/true, /*DecomposeAnd=*/true);
196 if (!Res)
197 return false;
198
199 Pred = Res->Pred;
200 X = Res->X;
201 Y = ConstantInt::get(Ty: X->getType(), V: Res->Mask);
202 Z = ConstantInt::get(Ty: X->getType(), V: Res->C);
203 return true;
204}
205
206/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
207/// Return the pattern classes (from MaskedICmpType) for the left hand side and
208/// the right hand side as a pair.
209/// LHS and RHS are the left hand side and the right hand side ICmps and PredL
210/// and PredR are their predicates, respectively.
211static std::optional<std::pair<unsigned, unsigned>>
212getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C, Value *&D, Value *&E,
213 Value *LHS, Value *RHS, ICmpInst::Predicate &PredL,
214 ICmpInst::Predicate &PredR) {
215
216 // Here comes the tricky part:
217 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
218 // and L11 & L12 == L21 & L22. The same goes for RHS.
219 // Now we must find those components L** and R**, that are equal, so
220 // that we can extract the parameters A, B, C, D, and E for the canonical
221 // above.
222
223 // Check whether the icmp can be decomposed into a bit test.
224 Value *L1, *L11, *L12, *L2, *L21, *L22;
225 if (decomposeBitTest(Cond: LHS, Pred&: PredL, X&: L11, Y&: L12, Z&: L2)) {
226 L21 = L22 = L1 = nullptr;
227 } else {
228 auto *LHSCMP = dyn_cast<ICmpInst>(Val: LHS);
229 if (!LHSCMP)
230 return std::nullopt;
231
232 // Don't allow pointers. Splat vectors are fine.
233 if (!LHSCMP->getOperand(i_nocapture: 0)->getType()->isIntOrIntVectorTy())
234 return std::nullopt;
235
236 PredL = LHSCMP->getPredicate();
237 L1 = LHSCMP->getOperand(i_nocapture: 0);
238 L2 = LHSCMP->getOperand(i_nocapture: 1);
239 // Look for ANDs in the LHS icmp.
240 if (!match(V: L1, P: m_And(L: m_Value(V&: L11), R: m_Value(V&: L12)))) {
241 // Any icmp can be viewed as being trivially masked; if it allows us to
242 // remove one, it's worth it.
243 L11 = L1;
244 L12 = Constant::getAllOnesValue(Ty: L1->getType());
245 }
246
247 if (!match(V: L2, P: m_And(L: m_Value(V&: L21), R: m_Value(V&: L22)))) {
248 L21 = L2;
249 L22 = Constant::getAllOnesValue(Ty: L2->getType());
250 }
251 }
252
253 // Bail if LHS was a icmp that can't be decomposed into an equality.
254 if (!ICmpInst::isEquality(P: PredL))
255 return std::nullopt;
256
257 Value *R11, *R12, *R2;
258 if (decomposeBitTest(Cond: RHS, Pred&: PredR, X&: R11, Y&: R12, Z&: R2)) {
259 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
260 A = R11;
261 D = R12;
262 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
263 A = R12;
264 D = R11;
265 } else {
266 return std::nullopt;
267 }
268 E = R2;
269 } else {
270 auto *RHSCMP = dyn_cast<ICmpInst>(Val: RHS);
271 if (!RHSCMP)
272 return std::nullopt;
273 // Don't allow pointers. Splat vectors are fine.
274 if (!RHSCMP->getOperand(i_nocapture: 0)->getType()->isIntOrIntVectorTy())
275 return std::nullopt;
276
277 PredR = RHSCMP->getPredicate();
278
279 Value *R1 = RHSCMP->getOperand(i_nocapture: 0);
280 R2 = RHSCMP->getOperand(i_nocapture: 1);
281 bool Ok = false;
282 if (!match(V: R1, P: m_And(L: m_Value(V&: R11), R: m_Value(V&: R12)))) {
283 // As before, model no mask as a trivial mask if it'll let us do an
284 // optimization.
285 R11 = R1;
286 R12 = Constant::getAllOnesValue(Ty: R1->getType());
287 }
288
289 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
290 A = R11;
291 D = R12;
292 E = R2;
293 Ok = true;
294 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
295 A = R12;
296 D = R11;
297 E = R2;
298 Ok = true;
299 }
300
301 // Avoid matching against the -1 value we created for unmasked operand.
302 if (Ok && match(V: A, P: m_AllOnes()))
303 Ok = false;
304
305 // Look for ANDs on the right side of the RHS icmp.
306 if (!Ok) {
307 if (!match(V: R2, P: m_And(L: m_Value(V&: R11), R: m_Value(V&: R12)))) {
308 R11 = R2;
309 R12 = Constant::getAllOnesValue(Ty: R2->getType());
310 }
311
312 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
313 A = R11;
314 D = R12;
315 E = R1;
316 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
317 A = R12;
318 D = R11;
319 E = R1;
320 } else {
321 return std::nullopt;
322 }
323 }
324 }
325
326 // Bail if RHS was a icmp that can't be decomposed into an equality.
327 if (!ICmpInst::isEquality(P: PredR))
328 return std::nullopt;
329
330 if (L11 == A) {
331 B = L12;
332 C = L2;
333 } else if (L12 == A) {
334 B = L11;
335 C = L2;
336 } else if (L21 == A) {
337 B = L22;
338 C = L1;
339 } else if (L22 == A) {
340 B = L21;
341 C = L1;
342 }
343
344 unsigned LeftType = getMaskedICmpType(A, B, C, Pred: PredL);
345 unsigned RightType = getMaskedICmpType(A, B: D, C: E, Pred: PredR);
346 return std::optional<std::pair<unsigned, unsigned>>(
347 std::make_pair(x&: LeftType, y&: RightType));
348}
349
350/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
351/// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
352/// and the right hand side is of type BMask_Mixed. For example,
353/// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
354/// Also used for logical and/or, must be poison safe.
355static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
356 Value *LHS, Value *RHS, bool IsAnd, Value *A, Value *B, Value *D, Value *E,
357 ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
358 InstCombiner::BuilderTy &Builder) {
359 // We are given the canonical form:
360 // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
361 // where D & E == E.
362 //
363 // If IsAnd is false, we get it in negated form:
364 // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
365 // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
366 //
367 // We currently handle the case of B, C, D, E are constant.
368 //
369 const APInt *BCst, *DCst, *OrigECst;
370 if (!match(V: B, P: m_APInt(Res&: BCst)) || !match(V: D, P: m_APInt(Res&: DCst)) ||
371 !match(V: E, P: m_APInt(Res&: OrigECst)))
372 return nullptr;
373
374 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
375
376 // Update E to the canonical form when D is a power of two and RHS is
377 // canonicalized as,
378 // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
379 // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
380 APInt ECst = *OrigECst;
381 if (PredR != NewCC)
382 ECst ^= *DCst;
383
384 // If B or D is zero, skip because if LHS or RHS can be trivially folded by
385 // other folding rules and this pattern won't apply any more.
386 if (*BCst == 0 || *DCst == 0)
387 return nullptr;
388
389 // If B and D don't intersect, ie. (B & D) == 0, try to fold isNaN idiom:
390 // (icmp ne (A & FractionBits), 0) & (icmp eq (A & ExpBits), ExpBits)
391 // -> isNaN(A)
392 // Otherwise, we cannot deduce anything from it.
393 if (!BCst->intersects(RHS: *DCst)) {
394 Value *Src;
395 if (*DCst == ECst && match(V: A, P: m_ElementWiseBitCast(Op: m_Value(V&: Src))) &&
396 !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
397 Kind: Attribute::StrictFP)) {
398 Type *Ty = Src->getType()->getScalarType();
399 if (!Ty->isIEEELikeFPTy())
400 return nullptr;
401
402 APInt ExpBits = APFloat::getInf(Sem: Ty->getFltSemantics()).bitcastToAPInt();
403 if (ECst != ExpBits)
404 return nullptr;
405 APInt FractionBits = ~ExpBits;
406 FractionBits.clearSignBit();
407 if (*BCst != FractionBits)
408 return nullptr;
409
410 return Builder.CreateFCmp(P: IsAnd ? FCmpInst::FCMP_UNO : FCmpInst::FCMP_ORD,
411 LHS: Src, RHS: ConstantFP::getZero(Ty: Src->getType()));
412 }
413 return nullptr;
414 }
415
416 // If the following two conditions are met:
417 //
418 // 1. mask B covers only a single bit that's not covered by mask D, that is,
419 // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
420 // B and D has only one bit set) and,
421 //
422 // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
423 // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
424 //
425 // then that single bit in B must be one and thus the whole expression can be
426 // folded to
427 // (A & (B | D)) == (B & (B ^ D)) | E.
428 //
429 // For example,
430 // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
431 // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
432 if ((((*BCst & *DCst) & ECst) == 0) &&
433 (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
434 APInt BorD = *BCst | *DCst;
435 APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
436 Value *NewMask = ConstantInt::get(Ty: A->getType(), V: BorD);
437 Value *NewMaskedValue = ConstantInt::get(Ty: A->getType(), V: BandBxorDorE);
438 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewMask);
439 return Builder.CreateICmp(P: NewCC, LHS: NewAnd, RHS: NewMaskedValue);
440 }
441
442 auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
443 return (*C1 & *C2) == *C1;
444 };
445 auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
446 return (*C1 & *C2) == *C2;
447 };
448
449 // In the following, we consider only the cases where B is a superset of D, B
450 // is a subset of D, or B == D because otherwise there's at least one bit
451 // covered by B but not D, in which case we can't deduce much from it, so
452 // no folding (aside from the single must-be-one bit case right above.)
453 // For example,
454 // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
455 if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
456 return nullptr;
457
458 // At this point, either B is a superset of D, B is a subset of D or B == D.
459
460 // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
461 // and the whole expression becomes false (or true if negated), otherwise, no
462 // folding.
463 // For example,
464 // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
465 // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
466 if (ECst.isZero()) {
467 if (IsSubSetOrEqual(BCst, DCst))
468 return ConstantInt::get(Ty: LHS->getType(), V: !IsAnd);
469 return nullptr;
470 }
471
472 // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
473 // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
474 // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
475 // RHS. For example,
476 // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
477 // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
478 if (IsSuperSetOrEqual(BCst, DCst)) {
479 // We can't guarantee that samesign hold after this fold.
480 if (auto *ICmp = dyn_cast<ICmpInst>(Val: RHS))
481 ICmp->setSameSign(false);
482 return RHS;
483 }
484 // Otherwise, B is a subset of D. If B and E have a common bit set,
485 // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
486 // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
487 assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
488 if ((*BCst & ECst) != 0) {
489 // We can't guarantee that samesign hold after this fold.
490 if (auto *ICmp = dyn_cast<ICmpInst>(Val: RHS))
491 ICmp->setSameSign(false);
492 return RHS;
493 }
494 // Otherwise, LHS and RHS contradict and the whole expression becomes false
495 // (or true if negated.) For example,
496 // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
497 // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
498 return ConstantInt::get(Ty: LHS->getType(), V: !IsAnd);
499}
500
501/// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
502/// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
503/// aren't of the common mask pattern type.
504/// Also used for logical and/or, must be poison safe.
505static Value *foldLogOpOfMaskedICmpsAsymmetric(
506 Value *LHS, Value *RHS, bool IsAnd, Value *A, Value *B, Value *C, Value *D,
507 Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
508 unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
509 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
510 "Expected equality predicates for masked type of icmps.");
511 // Handle Mask_NotAllZeros-BMask_Mixed cases.
512 // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
513 // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
514 // which gets swapped to
515 // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
516 if (!IsAnd) {
517 LHSMask = conjugateICmpMask(Mask: LHSMask);
518 RHSMask = conjugateICmpMask(Mask: RHSMask);
519 }
520 if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
521 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
522 LHS, RHS, IsAnd, A, B, D, E, PredL, PredR, Builder)) {
523 return V;
524 }
525 } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
526 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
527 LHS: RHS, RHS: LHS, IsAnd, A, B: D, D: B, E: C, PredL: PredR, PredR: PredL, Builder)) {
528 return V;
529 }
530 }
531 return nullptr;
532}
533
534/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
535/// into a single (icmp(A & X) ==/!= Y).
536static Value *foldLogOpOfMaskedICmps(Value *LHS, Value *RHS, bool IsAnd,
537 bool IsLogical,
538 InstCombiner::BuilderTy &Builder,
539 const SimplifyQuery &Q) {
540 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
541 ICmpInst::Predicate PredL, PredR;
542 std::optional<std::pair<unsigned, unsigned>> MaskPair =
543 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
544 if (!MaskPair)
545 return nullptr;
546 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
547 "Expected equality predicates for masked type of icmps.");
548 unsigned LHSMask = MaskPair->first;
549 unsigned RHSMask = MaskPair->second;
550 unsigned Mask = LHSMask & RHSMask;
551 if (Mask == 0) {
552 // Even if the two sides don't share a common pattern, check if folding can
553 // still happen.
554 if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
555 LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
556 Builder))
557 return V;
558 return nullptr;
559 }
560
561 // In full generality:
562 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
563 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
564 //
565 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
566 // equivalent to (icmp (A & X) !Op Y).
567 //
568 // Therefore, we can pretend for the rest of this function that we're dealing
569 // with the conjunction, provided we flip the sense of any comparisons (both
570 // input and output).
571
572 // In most cases we're going to produce an EQ for the "&&" case.
573 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
574 if (!IsAnd) {
575 // Convert the masking analysis into its equivalent with negated
576 // comparisons.
577 Mask = conjugateICmpMask(Mask);
578 }
579
580 if (Mask & Mask_AllZeros) {
581 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
582 // -> (icmp eq (A & (B|D)), 0)
583 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(V: D))
584 return nullptr; // TODO: Use freeze?
585 Value *NewOr = Builder.CreateOr(LHS: B, RHS: D);
586 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr);
587 // We can't use C as zero because we might actually handle
588 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
589 // with B and D, having a single bit set.
590 Value *Zero = Constant::getNullValue(Ty: A->getType());
591 return Builder.CreateICmp(P: NewCC, LHS: NewAnd, RHS: Zero);
592 }
593 if (Mask & BMask_AllOnes) {
594 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
595 // -> (icmp eq (A & (B|D)), (B|D))
596 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(V: D))
597 return nullptr; // TODO: Use freeze?
598 Value *NewOr = Builder.CreateOr(LHS: B, RHS: D);
599 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr);
600 return Builder.CreateICmp(P: NewCC, LHS: NewAnd, RHS: NewOr);
601 }
602 if (Mask & AMask_AllOnes) {
603 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
604 // -> (icmp eq (A & (B&D)), A)
605 if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(V: D))
606 return nullptr; // TODO: Use freeze?
607 Value *NewAnd1 = Builder.CreateAnd(LHS: B, RHS: D);
608 Value *NewAnd2 = Builder.CreateAnd(LHS: A, RHS: NewAnd1);
609 return Builder.CreateICmp(P: NewCC, LHS: NewAnd2, RHS: A);
610 }
611
612 const APInt *ConstB, *ConstD;
613 if (match(V: B, P: m_APInt(Res&: ConstB)) && match(V: D, P: m_APInt(Res&: ConstD))) {
614 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
615 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
616 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
617 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
618 // Only valid if one of the masks is a superset of the other (check "B&D"
619 // is the same as either B or D).
620 APInt NewMask = *ConstB & *ConstD;
621 if (NewMask == *ConstB)
622 return LHS;
623 if (NewMask == *ConstD) {
624 if (IsLogical) {
625 if (auto *RHSI = dyn_cast<Instruction>(Val: RHS))
626 RHSI->dropPoisonGeneratingFlags();
627 }
628 return RHS;
629 }
630 }
631
632 if (Mask & AMask_NotAllOnes) {
633 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
634 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
635 // Only valid if one of the masks is a superset of the other (check "B|D"
636 // is the same as either B or D).
637 APInt NewMask = *ConstB | *ConstD;
638 if (NewMask == *ConstB)
639 return LHS;
640 if (NewMask == *ConstD)
641 return RHS;
642 }
643
644 if (Mask & (BMask_Mixed | BMask_NotMixed)) {
645 // Mixed:
646 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
647 // We already know that B & C == C && D & E == E.
648 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
649 // C and E, which are shared by both the mask B and the mask D, don't
650 // contradict, then we can transform to
651 // -> (icmp eq (A & (B|D)), (C|E))
652 // Currently, we only handle the case of B, C, D, and E being constant.
653 // We can't simply use C and E because we might actually handle
654 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
655 // with B and D, having a single bit set.
656
657 // NotMixed:
658 // (icmp ne (A & B), C) & (icmp ne (A & D), E)
659 // -> (icmp ne (A & (B & D)), (C & E))
660 // Check the intersection (B & D) for inequality.
661 // Assume that (B & D) == B || (B & D) == D, i.e B/D is a subset of D/B
662 // and (B & D) & (C ^ E) == 0, bits of C and E, which are shared by both
663 // the B and the D, don't contradict. Note that we can assume (~B & C) ==
664 // 0 && (~D & E) == 0, previous operation should delete these icmps if it
665 // hadn't been met.
666
667 const APInt *OldConstC, *OldConstE;
668 if (!match(V: C, P: m_APInt(Res&: OldConstC)) || !match(V: E, P: m_APInt(Res&: OldConstE)))
669 return nullptr;
670
671 auto FoldBMixed = [&](ICmpInst::Predicate CC, bool IsNot) -> Value * {
672 CC = IsNot ? CmpInst::getInversePredicate(pred: CC) : CC;
673 const APInt ConstC = PredL != CC ? *ConstB ^ *OldConstC : *OldConstC;
674 const APInt ConstE = PredR != CC ? *ConstD ^ *OldConstE : *OldConstE;
675
676 if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
677 return IsNot ? nullptr : ConstantInt::get(Ty: LHS->getType(), V: !IsAnd);
678
679 if (IsNot && !ConstB->isSubsetOf(RHS: *ConstD) &&
680 !ConstD->isSubsetOf(RHS: *ConstB))
681 return nullptr;
682
683 APInt BD, CE;
684 if (IsNot) {
685 BD = *ConstB & *ConstD;
686 CE = ConstC & ConstE;
687 } else {
688 BD = *ConstB | *ConstD;
689 CE = ConstC | ConstE;
690 }
691 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: BD);
692 Value *CEVal = ConstantInt::get(Ty: A->getType(), V: CE);
693 return Builder.CreateICmp(P: CC, LHS: NewAnd, RHS: CEVal);
694 };
695
696 if (Mask & BMask_Mixed)
697 return FoldBMixed(NewCC, false);
698 if (Mask & BMask_NotMixed) // can be else also
699 return FoldBMixed(NewCC, true);
700 }
701 }
702
703 // (icmp eq (A & B), 0) | (icmp eq (A & D), 0)
704 // -> (icmp ne (A & (B|D)), (B|D))
705 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0)
706 // -> (icmp eq (A & (B|D)), (B|D))
707 // iff B and D is known to be a power of two
708 if (Mask & Mask_NotAllZeros &&
709 isKnownToBeAPowerOfTwo(V: B, /*OrZero=*/false, Q) &&
710 isKnownToBeAPowerOfTwo(V: D, /*OrZero=*/false, Q)) {
711 // If this is a logical and/or, then we must prevent propagation of a
712 // poison value from the RHS by inserting freeze.
713 if (IsLogical)
714 D = Builder.CreateFreeze(V: D);
715 Value *Mask = Builder.CreateOr(LHS: B, RHS: D);
716 Value *Masked = Builder.CreateAnd(LHS: A, RHS: Mask);
717 return Builder.CreateICmp(P: NewCC, LHS: Masked, RHS: Mask);
718 }
719 return nullptr;
720}
721
722/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
723/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
724/// If \p Inverted is true then the check is for the inverted range, e.g.
725/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
726Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
727 bool Inverted) {
728 // Check the lower range comparison, e.g. x >= 0
729 // InstCombine already ensured that if there is a constant it's on the RHS.
730 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Val: Cmp0->getOperand(i_nocapture: 1));
731 if (!RangeStart)
732 return nullptr;
733
734 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
735 Cmp0->getPredicate());
736
737 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
738 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
739 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
740 return nullptr;
741
742 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
743 Cmp1->getPredicate());
744
745 Value *Input = Cmp0->getOperand(i_nocapture: 0);
746 Value *Cmp1Op0 = Cmp1->getOperand(i_nocapture: 0);
747 Value *Cmp1Op1 = Cmp1->getOperand(i_nocapture: 1);
748 Value *RangeEnd;
749 if (match(V: Cmp1Op0, P: m_SExtOrSelf(Op: m_Specific(V: Input)))) {
750 // For the upper range compare we have: icmp x, n
751 Input = Cmp1Op0;
752 RangeEnd = Cmp1Op1;
753 } else if (match(V: Cmp1Op1, P: m_SExtOrSelf(Op: m_Specific(V: Input)))) {
754 // For the upper range compare we have: icmp n, x
755 Input = Cmp1Op1;
756 RangeEnd = Cmp1Op0;
757 Pred1 = ICmpInst::getSwappedPredicate(pred: Pred1);
758 } else {
759 return nullptr;
760 }
761
762 // Check the upper range comparison, e.g. x < n
763 ICmpInst::Predicate NewPred;
764 switch (Pred1) {
765 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
766 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
767 default: return nullptr;
768 }
769
770 // This simplification is only valid if the upper range is not negative.
771 KnownBits Known = computeKnownBits(V: RangeEnd, CxtI: Cmp1);
772 if (!Known.isNonNegative())
773 return nullptr;
774
775 if (Inverted)
776 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
777
778 return Builder.CreateICmp(P: NewPred, LHS: Input, RHS: RangeEnd);
779}
780
781// (or (icmp eq X, 0), (icmp eq X, Pow2OrZero))
782// -> (icmp eq (and X, Pow2OrZero), X)
783// (and (icmp ne X, 0), (icmp ne X, Pow2OrZero))
784// -> (icmp ne (and X, Pow2OrZero), X)
785static Value *
786foldAndOrOfICmpsWithPow2AndWithZero(InstCombiner::BuilderTy &Builder,
787 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
788 const SimplifyQuery &Q) {
789 CmpPredicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
790 // Make sure we have right compares for our op.
791 if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
792 return nullptr;
793
794 // Make it so we can match LHS against the (icmp eq/ne X, 0) just for
795 // simplicity.
796 if (match(V: RHS->getOperand(i_nocapture: 1), P: m_Zero()))
797 std::swap(a&: LHS, b&: RHS);
798
799 Value *Pow2, *Op;
800 // Match the desired pattern:
801 // LHS: (icmp eq/ne X, 0)
802 // RHS: (icmp eq/ne X, Pow2OrZero)
803 // Skip if Pow2OrZero is 1. Either way it gets folded to (icmp ugt X, 1) but
804 // this form ends up slightly less canonical.
805 // We could potentially be more sophisticated than requiring LHS/RHS
806 // be one-use. We don't create additional instructions if only one
807 // of them is one-use. So cases where one is one-use and the other
808 // is two-use might be profitable.
809 if (!match(V: LHS, P: m_OneUse(SubPattern: m_ICmp(Pred, L: m_Value(V&: Op), R: m_Zero()))) ||
810 !match(V: RHS, P: m_OneUse(SubPattern: m_c_ICmp(Pred, L: m_Specific(V: Op), R: m_Value(V&: Pow2)))) ||
811 match(V: Pow2, P: m_One()) ||
812 !isKnownToBeAPowerOfTwo(V: Pow2, DL: Q.DL, /*OrZero=*/true, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT))
813 return nullptr;
814
815 Value *And = Builder.CreateAnd(LHS: Op, RHS: Pow2);
816 return Builder.CreateICmp(P: Pred, LHS: And, RHS: Op);
817}
818
819/// General pattern:
820/// X & Y
821///
822/// Where Y is checking that all the high bits (covered by a mask 4294967168)
823/// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
824/// Pattern can be one of:
825/// %t = add i32 %arg, 128
826/// %r = icmp ult i32 %t, 256
827/// Or
828/// %t0 = shl i32 %arg, 24
829/// %t1 = ashr i32 %t0, 24
830/// %r = icmp eq i32 %t1, %arg
831/// Or
832/// %t0 = trunc i32 %arg to i8
833/// %t1 = sext i8 %t0 to i32
834/// %r = icmp eq i32 %t1, %arg
835/// This pattern is a signed truncation check.
836///
837/// And X is checking that some bit in that same mask is zero.
838/// I.e. can be one of:
839/// %r = icmp sgt i32 %arg, -1
840/// Or
841/// %t = and i32 %arg, 2147483648
842/// %r = icmp eq i32 %t, 0
843///
844/// Since we are checking that all the bits in that mask are the same,
845/// and a particular bit is zero, what we are really checking is that all the
846/// masked bits are zero.
847/// So this should be transformed to:
848/// %r = icmp ult i32 %arg, 128
849static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
850 Instruction &CxtI,
851 InstCombiner::BuilderTy &Builder) {
852 assert(CxtI.getOpcode() == Instruction::And);
853
854 // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
855 auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
856 APInt &SignBitMask) -> bool {
857 const APInt *I01, *I1; // powers of two; I1 == I01 << 1
858 if (!(match(V: ICmp, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT,
859 L: m_Add(L: m_Value(V&: X), R: m_Power2(V&: I01)),
860 R: m_Power2(V&: I1))) &&
861 I1->ugt(RHS: *I01) && I01->shl(shiftAmt: 1) == *I1))
862 return false;
863 // Which bit is the new sign bit as per the 'signed truncation' pattern?
864 SignBitMask = *I01;
865 return true;
866 };
867
868 // One icmp needs to be 'signed truncation check'.
869 // We need to match this first, else we will mismatch commutative cases.
870 Value *X1;
871 APInt HighestBit;
872 ICmpInst *OtherICmp;
873 if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
874 OtherICmp = ICmp0;
875 else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
876 OtherICmp = ICmp1;
877 else
878 return nullptr;
879
880 assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
881
882 // Try to match/decompose into: icmp eq (X & Mask), 0
883 auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
884 APInt &UnsetBitsMask) -> bool {
885 CmpPredicate Pred = ICmp->getPredicate();
886 // Can it be decomposed into icmp eq (X & Mask), 0 ?
887 auto Res = llvm::decomposeBitTestICmp(
888 LHS: ICmp->getOperand(i_nocapture: 0), RHS: ICmp->getOperand(i_nocapture: 1), Pred,
889 /*LookThroughTrunc=*/false, /*AllowNonZeroC=*/false,
890 /*DecomposeAnd=*/true);
891 if (Res && Res->Pred == ICmpInst::ICMP_EQ) {
892 X = Res->X;
893 UnsetBitsMask = Res->Mask;
894 return true;
895 }
896
897 return false;
898 };
899
900 // And the other icmp needs to be decomposable into a bit test.
901 Value *X0;
902 APInt UnsetBitsMask;
903 if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
904 return nullptr;
905
906 assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
907
908 // Are they working on the same value?
909 Value *X;
910 if (X1 == X0) {
911 // Ok as is.
912 X = X1;
913 } else if (match(V: X0, P: m_Trunc(Op: m_Specific(V: X1)))) {
914 UnsetBitsMask = UnsetBitsMask.zext(width: X1->getType()->getScalarSizeInBits());
915 X = X1;
916 } else
917 return nullptr;
918
919 // So which bits should be uniform as per the 'signed truncation check'?
920 // (all the bits starting with (i.e. including) HighestBit)
921 APInt SignBitsMask = ~(HighestBit - 1U);
922
923 // UnsetBitsMask must have some common bits with SignBitsMask,
924 if (!UnsetBitsMask.intersects(RHS: SignBitsMask))
925 return nullptr;
926
927 // Does UnsetBitsMask contain any bits outside of SignBitsMask?
928 if (!UnsetBitsMask.isSubsetOf(RHS: SignBitsMask)) {
929 APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
930 if (!OtherHighestBit.isPowerOf2())
931 return nullptr;
932 HighestBit = APIntOps::umin(A: HighestBit, B: OtherHighestBit);
933 }
934 // Else, if it does not, then all is ok as-is.
935
936 // %r = icmp ult %X, SignBit
937 return Builder.CreateICmpULT(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: HighestBit),
938 Name: CxtI.getName() + ".simplified");
939}
940
941/// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
942/// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
943/// Also used for logical and/or, must be poison safe if range attributes are
944/// dropped.
945static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
946 InstCombiner::BuilderTy &Builder,
947 InstCombinerImpl &IC) {
948 CmpPredicate Pred0, Pred1;
949 Value *X;
950 if (!match(V: Cmp0, P: m_ICmp(Pred&: Pred0, L: m_Ctpop(Op0: m_Value(V&: X)), R: m_SpecificInt(V: 1))) ||
951 !match(V: Cmp1, P: m_ICmp(Pred&: Pred1, L: m_Specific(V: X), R: m_ZeroInt())))
952 return nullptr;
953
954 auto *CtPop = cast<Instruction>(Val: Cmp0->getOperand(i_nocapture: 0));
955 if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE) {
956 // Drop range attributes and re-infer them in the next iteration.
957 CtPop->dropPoisonGeneratingAnnotations();
958 IC.addToWorklist(I: CtPop);
959 return Builder.CreateICmpUGT(LHS: CtPop, RHS: ConstantInt::get(Ty: CtPop->getType(), V: 1));
960 }
961 if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ) {
962 // Drop range attributes and re-infer them in the next iteration.
963 CtPop->dropPoisonGeneratingAnnotations();
964 IC.addToWorklist(I: CtPop);
965 return Builder.CreateICmpULT(LHS: CtPop, RHS: ConstantInt::get(Ty: CtPop->getType(), V: 2));
966 }
967
968 return nullptr;
969}
970
971/// Reduce a pair of compares that check if a value has exactly 1 bit set.
972/// Also used for logical and/or, must be poison safe if range attributes are
973/// dropped.
974static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
975 InstCombiner::BuilderTy &Builder,
976 InstCombinerImpl &IC) {
977 // Handle 'and' / 'or' commutation: make the equality check the first operand.
978 if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
979 std::swap(a&: Cmp0, b&: Cmp1);
980 else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
981 std::swap(a&: Cmp0, b&: Cmp1);
982
983 // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
984 Value *X;
985 if (JoinedByAnd &&
986 match(V: Cmp0, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: m_Value(V&: X), R: m_ZeroInt())) &&
987 match(V: Cmp1, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT, L: m_Ctpop(Op0: m_Specific(V: X)),
988 R: m_SpecificInt(V: 2)))) {
989 auto *CtPop = cast<Instruction>(Val: Cmp1->getOperand(i_nocapture: 0));
990 // Drop range attributes and re-infer them in the next iteration.
991 CtPop->dropPoisonGeneratingAnnotations();
992 IC.addToWorklist(I: CtPop);
993 return Builder.CreateICmpEQ(LHS: CtPop, RHS: ConstantInt::get(Ty: CtPop->getType(), V: 1));
994 }
995 // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
996 if (!JoinedByAnd &&
997 match(V: Cmp0, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: X), R: m_ZeroInt())) &&
998 match(V: Cmp1, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_UGT, L: m_Ctpop(Op0: m_Specific(V: X)),
999 R: m_SpecificInt(V: 1)))) {
1000 auto *CtPop = cast<Instruction>(Val: Cmp1->getOperand(i_nocapture: 0));
1001 // Drop range attributes and re-infer them in the next iteration.
1002 CtPop->dropPoisonGeneratingAnnotations();
1003 IC.addToWorklist(I: CtPop);
1004 return Builder.CreateICmpNE(LHS: CtPop, RHS: ConstantInt::get(Ty: CtPop->getType(), V: 1));
1005 }
1006 return nullptr;
1007}
1008
1009/// Try to fold (icmp(A & B) == 0) & (icmp(A & D) != E) into (icmp A u< D) iff
1010/// B is a contiguous set of ones starting from the most significant bit
1011/// (negative power of 2), D and E are equal, and D is a contiguous set of ones
1012/// starting at the most significant zero bit in B. Parameter B supports masking
1013/// using undef/poison in either scalar or vector values.
1014static Value *foldNegativePower2AndShiftedMask(
1015 Value *A, Value *B, Value *D, Value *E, ICmpInst::Predicate PredL,
1016 ICmpInst::Predicate PredR, InstCombiner::BuilderTy &Builder) {
1017 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
1018 "Expected equality predicates for masked type of icmps.");
1019 if (PredL != ICmpInst::ICMP_EQ || PredR != ICmpInst::ICMP_NE)
1020 return nullptr;
1021
1022 if (!match(V: B, P: m_NegatedPower2()) || !match(V: D, P: m_ShiftedMask()) ||
1023 !match(V: E, P: m_ShiftedMask()))
1024 return nullptr;
1025
1026 // Test scalar arguments for conversion. B has been validated earlier to be a
1027 // negative power of two and thus is guaranteed to have one or more contiguous
1028 // ones starting from the MSB followed by zero or more contiguous zeros. D has
1029 // been validated earlier to be a shifted set of one or more contiguous ones.
1030 // In order to match, B leading ones and D leading zeros should be equal. The
1031 // predicate that B be a negative power of 2 prevents the condition of there
1032 // ever being zero leading ones. Thus 0 == 0 cannot occur. The predicate that
1033 // D always be a shifted mask prevents the condition of D equaling 0. This
1034 // prevents matching the condition where B contains the maximum number of
1035 // leading one bits (-1) and D contains the maximum number of leading zero
1036 // bits (0).
1037 auto isReducible = [](const Value *B, const Value *D, const Value *E) {
1038 const APInt *BCst, *DCst, *ECst;
1039 return match(V: B, P: m_APIntAllowPoison(Res&: BCst)) && match(V: D, P: m_APInt(Res&: DCst)) &&
1040 match(V: E, P: m_APInt(Res&: ECst)) && *DCst == *ECst &&
1041 (isa<PoisonValue>(Val: B) ||
1042 (BCst->countLeadingOnes() == DCst->countLeadingZeros()));
1043 };
1044
1045 // Test vector type arguments for conversion.
1046 if (const auto *BVTy = dyn_cast<VectorType>(Val: B->getType())) {
1047 const auto *BFVTy = dyn_cast<FixedVectorType>(Val: BVTy);
1048 const auto *BConst = dyn_cast<Constant>(Val: B);
1049 const auto *DConst = dyn_cast<Constant>(Val: D);
1050 const auto *EConst = dyn_cast<Constant>(Val: E);
1051
1052 if (!BFVTy || !BConst || !DConst || !EConst)
1053 return nullptr;
1054
1055 for (unsigned I = 0; I != BFVTy->getNumElements(); ++I) {
1056 const auto *BElt = BConst->getAggregateElement(Elt: I);
1057 const auto *DElt = DConst->getAggregateElement(Elt: I);
1058 const auto *EElt = EConst->getAggregateElement(Elt: I);
1059
1060 if (!BElt || !DElt || !EElt)
1061 return nullptr;
1062 if (!isReducible(BElt, DElt, EElt))
1063 return nullptr;
1064 }
1065 } else {
1066 // Test scalar type arguments for conversion.
1067 if (!isReducible(B, D, E))
1068 return nullptr;
1069 }
1070 return Builder.CreateICmp(P: ICmpInst::ICMP_ULT, LHS: A, RHS: D);
1071}
1072
1073/// Try to fold ((icmp X u< P) & (icmp(X & M) != M)) or ((icmp X s> -1) &
1074/// (icmp(X & M) != M)) into (icmp X u< M). Where P is a power of 2, M < P, and
1075/// M is a contiguous shifted mask starting at the right most significant zero
1076/// bit in P. SGT is supported as when P is the largest representable power of
1077/// 2, an earlier optimization converts the expression into (icmp X s> -1).
1078/// Parameter P supports masking using undef/poison in either scalar or vector
1079/// values.
1080static Value *foldPowerOf2AndShiftedMask(ICmpInst *Cmp0, ICmpInst *Cmp1,
1081 bool JoinedByAnd,
1082 InstCombiner::BuilderTy &Builder) {
1083 if (!JoinedByAnd)
1084 return nullptr;
1085 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
1086 ICmpInst::Predicate CmpPred0, CmpPred1;
1087 // Assuming P is a 2^n, getMaskedTypeForICmpPair will normalize (icmp X u<
1088 // 2^n) into (icmp (X & ~(2^n-1)) == 0) and (icmp X s> -1) into (icmp (X &
1089 // SignMask) == 0).
1090 std::optional<std::pair<unsigned, unsigned>> MaskPair =
1091 getMaskedTypeForICmpPair(A, B, C, D, E, LHS: Cmp0, RHS: Cmp1, PredL&: CmpPred0, PredR&: CmpPred1);
1092 if (!MaskPair)
1093 return nullptr;
1094
1095 const auto compareBMask = BMask_NotMixed | BMask_NotAllOnes;
1096 unsigned CmpMask0 = MaskPair->first;
1097 unsigned CmpMask1 = MaskPair->second;
1098 if ((CmpMask0 & Mask_AllZeros) && (CmpMask1 == compareBMask)) {
1099 if (Value *V = foldNegativePower2AndShiftedMask(A, B, D, E, PredL: CmpPred0,
1100 PredR: CmpPred1, Builder))
1101 return V;
1102 } else if ((CmpMask0 == compareBMask) && (CmpMask1 & Mask_AllZeros)) {
1103 if (Value *V = foldNegativePower2AndShiftedMask(A, B: D, D: B, E: C, PredL: CmpPred1,
1104 PredR: CmpPred0, Builder))
1105 return V;
1106 }
1107 return nullptr;
1108}
1109
1110/// Commuted variants are assumed to be handled by calling this function again
1111/// with the parameters swapped.
1112static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
1113 ICmpInst *UnsignedICmp, bool IsAnd,
1114 const SimplifyQuery &Q,
1115 InstCombiner::BuilderTy &Builder) {
1116 Value *ZeroCmpOp;
1117 CmpPredicate EqPred;
1118 if (!match(V: ZeroICmp, P: m_ICmp(Pred&: EqPred, L: m_Value(V&: ZeroCmpOp), R: m_Zero())) ||
1119 !ICmpInst::isEquality(P: EqPred))
1120 return nullptr;
1121
1122 CmpPredicate UnsignedPred;
1123
1124 Value *A, *B;
1125 if (match(V: UnsignedICmp,
1126 P: m_c_ICmp(Pred&: UnsignedPred, L: m_Specific(V: ZeroCmpOp), R: m_Value(V&: A))) &&
1127 match(V: ZeroCmpOp, P: m_c_Add(L: m_Specific(V: A), R: m_Value(V&: B))) &&
1128 (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
1129 auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
1130 if (!isKnownNonZero(V: NonZero, Q))
1131 std::swap(a&: NonZero, b&: Other);
1132 return isKnownNonZero(V: NonZero, Q);
1133 };
1134
1135 // Given ZeroCmpOp = (A + B)
1136 // ZeroCmpOp < A && ZeroCmpOp != 0 --> (0-X) < Y iff
1137 // ZeroCmpOp >= A || ZeroCmpOp == 0 --> (0-X) >= Y iff
1138 // with X being the value (A/B) that is known to be non-zero,
1139 // and Y being remaining value.
1140 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
1141 IsAnd && GetKnownNonZeroAndOther(B, A))
1142 return Builder.CreateICmpULT(LHS: Builder.CreateNeg(V: B), RHS: A);
1143 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
1144 !IsAnd && GetKnownNonZeroAndOther(B, A))
1145 return Builder.CreateICmpUGE(LHS: Builder.CreateNeg(V: B), RHS: A);
1146 }
1147
1148 return nullptr;
1149}
1150
1151struct IntPart {
1152 Value *From;
1153 unsigned StartBit;
1154 unsigned NumBits;
1155};
1156
1157/// Match an extraction of bits from an integer.
1158static std::optional<IntPart> matchIntPart(Value *V) {
1159 Value *X;
1160 if (!match(V, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))))
1161 return std::nullopt;
1162
1163 unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1164 unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1165 Value *Y;
1166 const APInt *Shift;
1167 // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1168 // from Y, not any shifted-in zeroes.
1169 if (match(V: X, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: Y), R: m_APInt(Res&: Shift)))) &&
1170 Shift->ule(RHS: NumOriginalBits - NumExtractedBits))
1171 return {{.From: Y, .StartBit: (unsigned)Shift->getZExtValue(), .NumBits: NumExtractedBits}};
1172 return {{.From: X, .StartBit: 0, .NumBits: NumExtractedBits}};
1173}
1174
1175/// Materialize an extraction of bits from an integer in IR.
1176static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1177 Value *V = P.From;
1178 if (P.StartBit)
1179 V = Builder.CreateLShr(LHS: V, RHS: P.StartBit);
1180 Type *TruncTy = V->getType()->getWithNewBitWidth(NewBitWidth: P.NumBits);
1181 if (TruncTy != V->getType())
1182 V = Builder.CreateTrunc(V, DestTy: TruncTy);
1183 return V;
1184}
1185
1186/// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1187/// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1188/// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1189Value *InstCombinerImpl::foldEqOfParts(Value *Cmp0, Value *Cmp1, bool IsAnd) {
1190 if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1191 return nullptr;
1192
1193 CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1194 auto GetMatchPart = [&](Value *CmpV,
1195 unsigned OpNo) -> std::optional<IntPart> {
1196 assert(CmpV->getType()->isIntOrIntVectorTy(1) && "Must be bool");
1197
1198 Value *X, *Y;
1199 // icmp ne (and x, 1), (and y, 1) <=> trunc (xor x, y) to i1
1200 // icmp eq (and x, 1), (and y, 1) <=> not (trunc (xor x, y) to i1)
1201 if (Pred == CmpInst::ICMP_NE
1202 ? match(V: CmpV, P: m_Trunc(Op: m_Xor(L: m_Value(V&: X), R: m_Value(V&: Y))))
1203 : match(V: CmpV, P: m_Not(V: m_Trunc(Op: m_Xor(L: m_Value(V&: X), R: m_Value(V&: Y))))))
1204 return {{.From: OpNo == 0 ? X : Y, .StartBit: 0, .NumBits: 1}};
1205
1206 auto *Cmp = dyn_cast<ICmpInst>(Val: CmpV);
1207 if (!Cmp)
1208 return std::nullopt;
1209
1210 if (Pred == Cmp->getPredicate())
1211 return matchIntPart(V: Cmp->getOperand(i_nocapture: OpNo));
1212
1213 const APInt *C;
1214 // (icmp eq (lshr x, C), (lshr y, C)) gets optimized to:
1215 // (icmp ult (xor x, y), 1 << C) so also look for that.
1216 if (Pred == CmpInst::ICMP_EQ && Cmp->getPredicate() == CmpInst::ICMP_ULT) {
1217 if (!match(V: Cmp->getOperand(i_nocapture: 1), P: m_Power2(V&: C)) ||
1218 !match(V: Cmp->getOperand(i_nocapture: 0), P: m_Xor(L: m_Value(), R: m_Value())))
1219 return std::nullopt;
1220 }
1221
1222 // (icmp ne (lshr x, C), (lshr y, C)) gets optimized to:
1223 // (icmp ugt (xor x, y), (1 << C) - 1) so also look for that.
1224 else if (Pred == CmpInst::ICMP_NE &&
1225 Cmp->getPredicate() == CmpInst::ICMP_UGT) {
1226 if (!match(V: Cmp->getOperand(i_nocapture: 1), P: m_LowBitMask(V&: C)) ||
1227 !match(V: Cmp->getOperand(i_nocapture: 0), P: m_Xor(L: m_Value(), R: m_Value())))
1228 return std::nullopt;
1229 } else {
1230 return std::nullopt;
1231 }
1232
1233 unsigned From = Pred == CmpInst::ICMP_NE ? C->popcount() : C->countr_zero();
1234 Instruction *I = cast<Instruction>(Val: Cmp->getOperand(i_nocapture: 0));
1235 return {{.From: I->getOperand(i: OpNo), .StartBit: From, .NumBits: C->getBitWidth() - From}};
1236 };
1237
1238 std::optional<IntPart> L0 = GetMatchPart(Cmp0, 0);
1239 std::optional<IntPart> R0 = GetMatchPart(Cmp0, 1);
1240 std::optional<IntPart> L1 = GetMatchPart(Cmp1, 0);
1241 std::optional<IntPart> R1 = GetMatchPart(Cmp1, 1);
1242 if (!L0 || !R0 || !L1 || !R1)
1243 return nullptr;
1244
1245 // Make sure the LHS/RHS compare a part of the same value, possibly after
1246 // an operand swap.
1247 if (L0->From != L1->From || R0->From != R1->From) {
1248 if (L0->From != R1->From || R0->From != L1->From)
1249 return nullptr;
1250 std::swap(lhs&: L1, rhs&: R1);
1251 }
1252
1253 // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1254 // the low part and L1/R1 being the high part.
1255 if (L0->StartBit + L0->NumBits != L1->StartBit ||
1256 R0->StartBit + R0->NumBits != R1->StartBit) {
1257 if (L1->StartBit + L1->NumBits != L0->StartBit ||
1258 R1->StartBit + R1->NumBits != R0->StartBit)
1259 return nullptr;
1260 std::swap(lhs&: L0, rhs&: L1);
1261 std::swap(lhs&: R0, rhs&: R1);
1262 }
1263
1264 // We can simplify to a comparison of these larger parts of the integers.
1265 IntPart L = {.From: L0->From, .StartBit: L0->StartBit, .NumBits: L0->NumBits + L1->NumBits};
1266 IntPart R = {.From: R0->From, .StartBit: R0->StartBit, .NumBits: R0->NumBits + R1->NumBits};
1267 Value *LValue = extractIntPart(P: L, Builder);
1268 Value *RValue = extractIntPart(P: R, Builder);
1269 return Builder.CreateICmp(P: Pred, LHS: LValue, RHS: RValue);
1270}
1271
1272/// Reduce logic-of-compares with equality to a constant by substituting a
1273/// common operand with the constant. Callers are expected to call this with
1274/// Cmp0/Cmp1 switched to handle logic op commutativity.
1275static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1276 bool IsAnd, bool IsLogical,
1277 InstCombiner::BuilderTy &Builder,
1278 const SimplifyQuery &Q,
1279 Instruction &I) {
1280 // Match an equality compare with a non-poison constant as Cmp0.
1281 // Also, give up if the compare can be constant-folded to avoid looping.
1282 CmpPredicate Pred0;
1283 Value *X;
1284 Constant *C;
1285 if (!match(V: Cmp0, P: m_ICmp(Pred&: Pred0, L: m_Value(V&: X), R: m_Constant(C))) ||
1286 !isGuaranteedNotToBeUndefOrPoison(V: C) || isa<Constant>(Val: X))
1287 return nullptr;
1288 if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1289 (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1290 return nullptr;
1291
1292 // The other compare must include a common operand (X). Canonicalize the
1293 // common operand as operand 1 (Pred1 is swapped if the common operand was
1294 // operand 0).
1295 Value *Y;
1296 CmpPredicate Pred1;
1297 if (!match(V: Cmp1, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: Y), R: m_Specific(V: X))))
1298 return nullptr;
1299
1300 // Replace variable with constant value equivalence to remove a variable use:
1301 // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1302 // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1303 // Can think of the 'or' substitution with the 'and' bool equivalent:
1304 // A || B --> A || (!A && B)
1305 Value *SubstituteCmp = simplifyICmpInst(Pred: Pred1, LHS: Y, RHS: C, Q);
1306 if (!SubstituteCmp) {
1307 // If we need to create a new instruction, require that the old compare can
1308 // be removed.
1309 if (!Cmp1->hasOneUse())
1310 return nullptr;
1311 SubstituteCmp = Builder.CreateICmp(P: Pred1, LHS: Y, RHS: C);
1312 }
1313 if (IsLogical) {
1314 Instruction *MDFrom =
1315 ProfcheckDisableMetadataFixes && isa<SelectInst>(Val: I) ? nullptr : &I;
1316 return IsAnd ? Builder.CreateLogicalAnd(Cond1: Cmp0, Cond2: SubstituteCmp, Name: "", MDFrom)
1317 : Builder.CreateLogicalOr(Cond1: Cmp0, Cond2: SubstituteCmp, Name: "", MDFrom);
1318 }
1319 return Builder.CreateBinOp(Opc: IsAnd ? Instruction::And : Instruction::Or, LHS: Cmp0,
1320 RHS: SubstituteCmp);
1321}
1322
1323/// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1324/// or (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1325/// into a single comparison using range-based reasoning.
1326/// NOTE: This is also used for logical and/or, must be poison-safe!
1327Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
1328 ICmpInst *ICmp2,
1329 bool IsAnd) {
1330 // Return (V, CR) for a range check idiom V in CR.
1331 auto MatchExactRangeCheck =
1332 [](ICmpInst *ICmp) -> std::optional<std::pair<Value *, ConstantRange>> {
1333 const APInt *C;
1334 if (!match(V: ICmp->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)))
1335 return std::nullopt;
1336 Value *LHS = ICmp->getOperand(i_nocapture: 0);
1337 CmpPredicate Pred = ICmp->getPredicate();
1338 Value *X;
1339 // Match (x & NegPow2) ==/!= C
1340 const APInt *Mask;
1341 if (ICmpInst::isEquality(P: Pred) &&
1342 match(V: LHS, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_NegatedPower2(V&: Mask)))) &&
1343 C->countr_zero() >= Mask->countr_zero()) {
1344 ConstantRange CR(*C, *C - *Mask);
1345 if (Pred == ICmpInst::ICMP_NE)
1346 CR = CR.inverse();
1347 return std::make_pair(x&: X, y&: CR);
1348 }
1349 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1350 // Match (add X, C1) pred C
1351 // TODO: investigate whether we should apply the one-use check on m_AddLike.
1352 const APInt *C1;
1353 if (match(V: LHS, P: m_AddLike(L: m_Value(V&: X), R: m_APInt(Res&: C1))))
1354 return std::make_pair(x&: X, y: CR.subtract(CI: *C1));
1355 return std::make_pair(x&: LHS, y&: CR);
1356 };
1357
1358 auto RC1 = MatchExactRangeCheck(ICmp1);
1359 if (!RC1)
1360 return nullptr;
1361
1362 auto RC2 = MatchExactRangeCheck(ICmp2);
1363 if (!RC2)
1364 return nullptr;
1365
1366 auto &[V1, CR1] = *RC1;
1367 auto &[V2, CR2] = *RC2;
1368 if (V1 != V2)
1369 return nullptr;
1370
1371 // For 'and', we use the De Morgan's Laws to simplify the implementation.
1372 if (IsAnd) {
1373 CR1 = CR1.inverse();
1374 CR2 = CR2.inverse();
1375 }
1376
1377 Type *Ty = V1->getType();
1378 Value *NewV = V1;
1379 std::optional<ConstantRange> CR = CR1.exactUnionWith(CR: CR2);
1380 if (!CR) {
1381 if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
1382 CR2.isWrappedSet())
1383 return nullptr;
1384
1385 // Check whether we have equal-size ranges that only differ by one bit.
1386 // In that case we can apply a mask to map one range onto the other.
1387 APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
1388 APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
1389 APInt CR1Size = CR1.getUpper() - CR1.getLower();
1390 if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
1391 CR1Size != CR2.getUpper() - CR2.getLower())
1392 return nullptr;
1393
1394 CR = CR1.getLower().ult(RHS: CR2.getLower()) ? CR1 : CR2;
1395 NewV = Builder.CreateAnd(LHS: NewV, RHS: ConstantInt::get(Ty, V: ~LowerDiff));
1396 }
1397
1398 if (IsAnd)
1399 CR = CR->inverse();
1400
1401 CmpInst::Predicate NewPred;
1402 APInt NewC, Offset;
1403 CR->getEquivalentICmp(Pred&: NewPred, RHS&: NewC, Offset);
1404
1405 if (Offset != 0)
1406 NewV = Builder.CreateAdd(LHS: NewV, RHS: ConstantInt::get(Ty, V: Offset));
1407 return Builder.CreateICmp(P: NewPred, LHS: NewV, RHS: ConstantInt::get(Ty, V: NewC));
1408}
1409
1410/// Matches canonical form of isnan, fcmp ord x, 0
1411static bool matchIsNotNaN(FCmpInst::Predicate P, Value *LHS, Value *RHS) {
1412 return P == FCmpInst::FCMP_ORD && match(V: RHS, P: m_AnyZeroFP());
1413}
1414
1415/// Matches fcmp u__ x, +/-inf
1416static bool matchUnorderedInfCompare(FCmpInst::Predicate P, Value *LHS,
1417 Value *RHS) {
1418 return FCmpInst::isUnordered(predicate: P) && match(V: RHS, P: m_Inf());
1419}
1420
1421/// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1422///
1423/// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
1424static Value *matchIsFiniteTest(InstCombiner::BuilderTy &Builder, FCmpInst *LHS,
1425 FCmpInst *RHS) {
1426 Value *LHS0 = LHS->getOperand(i_nocapture: 0), *LHS1 = LHS->getOperand(i_nocapture: 1);
1427 Value *RHS0 = RHS->getOperand(i_nocapture: 0), *RHS1 = RHS->getOperand(i_nocapture: 1);
1428 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1429
1430 if (!matchIsNotNaN(P: PredL, LHS: LHS0, RHS: LHS1) ||
1431 !matchUnorderedInfCompare(P: PredR, LHS: RHS0, RHS: RHS1))
1432 return nullptr;
1433
1434 return Builder.CreateFCmpFMF(P: FCmpInst::getOrderedPredicate(Pred: PredR), LHS: RHS0, RHS: RHS1,
1435 FMFSource: FMFSource::intersect(A: LHS, B: RHS));
1436}
1437
1438Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1439 bool IsAnd, bool IsLogicalSelect) {
1440 Value *LHS0 = LHS->getOperand(i_nocapture: 0), *LHS1 = LHS->getOperand(i_nocapture: 1);
1441 Value *RHS0 = RHS->getOperand(i_nocapture: 0), *RHS1 = RHS->getOperand(i_nocapture: 1);
1442 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1443
1444 if (LHS0 == RHS1 && RHS0 == LHS1) {
1445 // Swap RHS operands to match LHS.
1446 PredR = FCmpInst::getSwappedPredicate(pred: PredR);
1447 std::swap(a&: RHS0, b&: RHS1);
1448 }
1449
1450 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1451 // Suppose the relation between x and y is R, where R is one of
1452 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1453 // testing the desired relations.
1454 //
1455 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1456 // bool(R & CC0) && bool(R & CC1)
1457 // = bool((R & CC0) & (R & CC1))
1458 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1459 //
1460 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1461 // bool(R & CC0) || bool(R & CC1)
1462 // = bool((R & CC0) | (R & CC1))
1463 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1464 if (LHS0 == RHS0 && LHS1 == RHS1) {
1465 unsigned FCmpCodeL = getFCmpCode(CC: PredL);
1466 unsigned FCmpCodeR = getFCmpCode(CC: PredR);
1467 unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1468
1469 // Intersect the fast math flags.
1470 // TODO: We can union the fast math flags unless this is a logical select.
1471 return getFCmpValue(Code: NewPred, LHS: LHS0, RHS: LHS1, Builder,
1472 FMF: FMFSource::intersect(A: LHS, B: RHS));
1473 }
1474
1475 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1476 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1477 if (LHS0->getType() != RHS0->getType())
1478 return nullptr;
1479
1480 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1481 // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1482 if (match(V: LHS1, P: m_PosZeroFP()) && match(V: RHS1, P: m_PosZeroFP())) {
1483 // Ignore the constants because they are obviously not NANs:
1484 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
1485 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
1486 Value *Y = RHS0;
1487 FastMathFlags FMF = LHS->getFastMathFlags() & RHS->getFastMathFlags();
1488 if (IsLogicalSelect) {
1489 Y = Builder.CreateFreeze(V: Y, Name: Y->getName() + ".fr");
1490 FMF.setNoNaNs(false);
1491 FMF.setNoInfs(false);
1492 }
1493 return Builder.CreateFCmpFMF(P: PredL, LHS: LHS0, RHS: Y, FMFSource: FMF);
1494 }
1495 }
1496
1497 // This transform is not valid for a logical select.
1498 if (!IsLogicalSelect && IsAnd &&
1499 stripSignOnlyFPOps(Val: LHS0) == stripSignOnlyFPOps(Val: RHS0)) {
1500 // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1501 // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
1502 if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
1503 return Left;
1504 if (Value *Right = matchIsFiniteTest(Builder, LHS: RHS, RHS: LHS))
1505 return Right;
1506 }
1507
1508 // Turn at least two fcmps with constants into llvm.is.fpclass.
1509 //
1510 // If we can represent a combined value test with one class call, we can
1511 // potentially eliminate 4-6 instructions. If we can represent a test with a
1512 // single fcmp with fneg and fabs, that's likely a better canonical form.
1513 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1514 auto [ClassValRHS, ClassMaskRHS] =
1515 fcmpToClassTest(Pred: PredR, F: *RHS->getFunction(), LHS: RHS0, RHS: RHS1);
1516 if (ClassValRHS) {
1517 auto [ClassValLHS, ClassMaskLHS] =
1518 fcmpToClassTest(Pred: PredL, F: *LHS->getFunction(), LHS: LHS0, RHS: LHS1);
1519 if (ClassValLHS == ClassValRHS) {
1520 unsigned CombinedMask = IsAnd ? (ClassMaskLHS & ClassMaskRHS)
1521 : (ClassMaskLHS | ClassMaskRHS);
1522 return Builder.CreateIntrinsic(
1523 ID: Intrinsic::is_fpclass, OverloadTypes: {ClassValLHS->getType()},
1524 Args: {ClassValLHS, Builder.getInt32(C: CombinedMask)});
1525 }
1526 }
1527 }
1528
1529 // Canonicalize the range check idiom:
1530 // and (fcmp olt/ole/ult/ule x, C), (fcmp ogt/oge/ugt/uge x, -C)
1531 // --> fabs(x) olt/ole/ult/ule C
1532 // or (fcmp ogt/oge/ugt/uge x, C), (fcmp olt/ole/ult/ule x, -C)
1533 // --> fabs(x) ogt/oge/ugt/uge C
1534 // TODO: Generalize to handle a negated variable operand?
1535 const APFloat *LHSC, *RHSC;
1536 if (LHS0 == RHS0 && LHS->hasOneUse() && RHS->hasOneUse() &&
1537 FCmpInst::getSwappedPredicate(pred: PredL) == PredR &&
1538 match(V: LHS1, P: m_APFloatAllowPoison(Res&: LHSC)) &&
1539 match(V: RHS1, P: m_APFloatAllowPoison(Res&: RHSC)) &&
1540 LHSC->bitwiseIsEqual(RHS: neg(X: *RHSC))) {
1541 auto IsLessThanOrLessEqual = [](FCmpInst::Predicate Pred) {
1542 switch (Pred) {
1543 case FCmpInst::FCMP_OLT:
1544 case FCmpInst::FCMP_OLE:
1545 case FCmpInst::FCMP_ULT:
1546 case FCmpInst::FCMP_ULE:
1547 return true;
1548 default:
1549 return false;
1550 }
1551 };
1552 if (IsLessThanOrLessEqual(IsAnd ? PredR : PredL)) {
1553 std::swap(a&: LHSC, b&: RHSC);
1554 std::swap(a&: PredL, b&: PredR);
1555 }
1556 if (IsLessThanOrLessEqual(IsAnd ? PredL : PredR)) {
1557 FastMathFlags NewFlag = LHS->getFastMathFlags();
1558 if (!IsLogicalSelect)
1559 NewFlag |= RHS->getFastMathFlags();
1560
1561 Value *FAbs = Builder.CreateFAbs(V: LHS0, FMFSource: NewFlag);
1562 return Builder.CreateFCmpFMF(
1563 P: PredL, LHS: FAbs, RHS: ConstantFP::get(Ty: LHS0->getType(), V: *LHSC), FMFSource: NewFlag);
1564 }
1565 }
1566
1567 return nullptr;
1568}
1569
1570/// Match an fcmp against a special value that performs a test possible by
1571/// llvm.is.fpclass.
1572static bool matchIsFPClassLikeFCmp(Value *Op, Value *&ClassVal,
1573 uint64_t &ClassMask) {
1574 auto *FCmp = dyn_cast<FCmpInst>(Val: Op);
1575 if (!FCmp || !FCmp->hasOneUse())
1576 return false;
1577
1578 std::tie(args&: ClassVal, args&: ClassMask) =
1579 fcmpToClassTest(Pred: FCmp->getPredicate(), F: *FCmp->getParent()->getParent(),
1580 LHS: FCmp->getOperand(i_nocapture: 0), RHS: FCmp->getOperand(i_nocapture: 1));
1581 return ClassVal != nullptr;
1582}
1583
1584/// or (is_fpclass x, mask0), (is_fpclass x, mask1)
1585/// -> is_fpclass x, (mask0 | mask1)
1586/// and (is_fpclass x, mask0), (is_fpclass x, mask1)
1587/// -> is_fpclass x, (mask0 & mask1)
1588/// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
1589/// -> is_fpclass x, (mask0 ^ mask1)
1590Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
1591 Value *Op0, Value *Op1) {
1592 Value *ClassVal0 = nullptr;
1593 Value *ClassVal1 = nullptr;
1594 uint64_t ClassMask0, ClassMask1;
1595
1596 // Restrict to folding one fcmp into one is.fpclass for now, don't introduce a
1597 // new class.
1598 //
1599 // TODO: Support forming is.fpclass out of 2 separate fcmps when codegen is
1600 // better.
1601
1602 bool IsLHSClass =
1603 match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::is_fpclass>(
1604 Ops: m_Value(V&: ClassVal0), Ops: m_ConstantInt(V&: ClassMask0))));
1605 bool IsRHSClass =
1606 match(V: Op1, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::is_fpclass>(
1607 Ops: m_Value(V&: ClassVal1), Ops: m_ConstantInt(V&: ClassMask1))));
1608 if ((((IsLHSClass || matchIsFPClassLikeFCmp(Op: Op0, ClassVal&: ClassVal0, ClassMask&: ClassMask0)) &&
1609 (IsRHSClass || matchIsFPClassLikeFCmp(Op: Op1, ClassVal&: ClassVal1, ClassMask&: ClassMask1)))) &&
1610 ClassVal0 == ClassVal1) {
1611 unsigned NewClassMask;
1612 switch (BO.getOpcode()) {
1613 case Instruction::And:
1614 NewClassMask = ClassMask0 & ClassMask1;
1615 break;
1616 case Instruction::Or:
1617 NewClassMask = ClassMask0 | ClassMask1;
1618 break;
1619 case Instruction::Xor:
1620 NewClassMask = ClassMask0 ^ ClassMask1;
1621 break;
1622 default:
1623 llvm_unreachable("not a binary logic operator");
1624 }
1625
1626 if (IsLHSClass) {
1627 auto *II = cast<IntrinsicInst>(Val: Op0);
1628 II->setArgOperand(
1629 i: 1, v: ConstantInt::get(Ty: II->getArgOperand(i: 1)->getType(), V: NewClassMask));
1630 return replaceInstUsesWith(I&: BO, V: II);
1631 }
1632
1633 if (IsRHSClass) {
1634 auto *II = cast<IntrinsicInst>(Val: Op1);
1635 II->setArgOperand(
1636 i: 1, v: ConstantInt::get(Ty: II->getArgOperand(i: 1)->getType(), V: NewClassMask));
1637 return replaceInstUsesWith(I&: BO, V: II);
1638 }
1639
1640 Value *NewClass =
1641 Builder.CreateIntrinsic(ID: Intrinsic::is_fpclass, OverloadTypes: {ClassVal0->getType()},
1642 Args: {ClassVal0, Builder.getInt32(C: NewClassMask)});
1643 return replaceInstUsesWith(I&: BO, V: NewClass);
1644 }
1645
1646 return nullptr;
1647}
1648
1649/// Look for the pattern that conditionally negates a value via math operations:
1650/// cond.splat = sext i1 cond
1651/// sub = add cond.splat, x
1652/// xor = xor sub, cond.splat
1653/// and rewrite it to do the same, but via logical operations:
1654/// value.neg = sub 0, value
1655/// cond = select i1 neg, value.neg, value
1656Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
1657 BinaryOperator &I) {
1658 assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
1659 Value *Cond, *X;
1660 // As per complexity ordering, `xor` is not commutative here.
1661 if (!match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Value()), R: m_Value())) ||
1662 !match(V: I.getOperand(i_nocapture: 1), P: m_SExt(Op: m_Value(V&: Cond))) ||
1663 !Cond->getType()->isIntOrIntVectorTy(BitWidth: 1) ||
1664 !match(V: I.getOperand(i_nocapture: 0), P: m_c_Add(L: m_SExt(Op: m_Specific(V: Cond)), R: m_Value(V&: X))))
1665 return nullptr;
1666 return createSelectInstWithUnknownProfile(
1667 C: Cond, S1: Builder.CreateNeg(V: X, Name: X->getName() + ".neg"), S2: X);
1668}
1669
1670/// This a limited reassociation for a special case (see above) where we are
1671/// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1672/// This could be handled more generally in '-reassociation', but it seems like
1673/// an unlikely pattern for a large number of logic ops and fcmps.
1674static Instruction *reassociateFCmps(BinaryOperator &BO,
1675 InstCombiner::BuilderTy &Builder) {
1676 Instruction::BinaryOps Opcode = BO.getOpcode();
1677 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1678 "Expecting and/or op for fcmp transform");
1679
1680 // There are 4 commuted variants of the pattern. Canonicalize operands of this
1681 // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1682 Value *Op0 = BO.getOperand(i_nocapture: 0), *Op1 = BO.getOperand(i_nocapture: 1), *X;
1683 if (match(V: Op1, P: m_FCmp(L: m_Value(), R: m_AnyZeroFP())))
1684 std::swap(a&: Op0, b&: Op1);
1685
1686 // Match inner binop and the predicate for combining 2 NAN checks into 1.
1687 Value *BO10, *BO11;
1688 FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1689 : FCmpInst::FCMP_UNO;
1690 if (!match(V: Op0, P: m_SpecificFCmp(MatchPred: NanPred, L: m_Value(V&: X), R: m_AnyZeroFP())) ||
1691 !match(V: Op1, P: m_BinOp(Opcode, L: m_Value(V&: BO10), R: m_Value(V&: BO11))))
1692 return nullptr;
1693
1694 // The inner logic op must have a matching fcmp operand.
1695 Value *Y;
1696 if (!match(V: BO10, P: m_SpecificFCmp(MatchPred: NanPred, L: m_Value(V&: Y), R: m_AnyZeroFP())) ||
1697 X->getType() != Y->getType())
1698 std::swap(a&: BO10, b&: BO11);
1699
1700 if (!match(V: BO10, P: m_SpecificFCmp(MatchPred: NanPred, L: m_Value(V&: Y), R: m_AnyZeroFP())) ||
1701 X->getType() != Y->getType())
1702 return nullptr;
1703
1704 // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1705 // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z
1706 // Intersect FMF from the 2 source fcmps.
1707 Value *NewFCmp =
1708 Builder.CreateFCmpFMF(P: NanPred, LHS: X, RHS: Y, FMFSource: FMFSource::intersect(A: Op0, B: BO10));
1709 return BinaryOperator::Create(Op: Opcode, S1: NewFCmp, S2: BO11);
1710}
1711
1712/// Match variations of De Morgan's Laws:
1713/// (~A & ~B) == (~(A | B))
1714/// (~A | ~B) == (~(A & B))
1715static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1716 InstCombiner &IC) {
1717 const Instruction::BinaryOps Opcode = I.getOpcode();
1718 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1719 "Trying to match De Morgan's Laws with something other than and/or");
1720
1721 // Flip the logic operation.
1722 const Instruction::BinaryOps FlippedOpcode =
1723 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1724
1725 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1726 Value *A, *B;
1727 if (match(V: Op0, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: A)))) &&
1728 match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: B)))) &&
1729 !IC.isFreeToInvert(V: A, WillInvertAllUses: A->hasOneUse()) &&
1730 !IC.isFreeToInvert(V: B, WillInvertAllUses: B->hasOneUse())) {
1731 Value *AndOr =
1732 IC.Builder.CreateBinOp(Opc: FlippedOpcode, LHS: A, RHS: B, Name: I.getName() + ".demorgan");
1733 return BinaryOperator::CreateNot(Op: AndOr);
1734 }
1735
1736 // The 'not' ops may require reassociation.
1737 // (A & ~B) & ~C --> A & ~(B | C)
1738 // (~B & A) & ~C --> A & ~(B | C)
1739 // (A | ~B) | ~C --> A | ~(B & C)
1740 // (~B | A) | ~C --> A | ~(B & C)
1741 Value *C;
1742 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_BinOp(Opcode, L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B))))) &&
1743 match(V: Op1, P: m_Not(V: m_Value(V&: C)))) {
1744 Value *FlippedBO = IC.Builder.CreateBinOp(Opc: FlippedOpcode, LHS: B, RHS: C);
1745 return BinaryOperator::Create(Op: Opcode, S1: A, S2: IC.Builder.CreateNot(V: FlippedBO));
1746 }
1747
1748 return nullptr;
1749}
1750
1751bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1752 Value *CastSrc = CI->getOperand(i_nocapture: 0);
1753
1754 // Noop casts and casts of constants should be eliminated trivially.
1755 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(Val: CastSrc))
1756 return false;
1757
1758 // If this cast is paired with another cast that can be eliminated, we prefer
1759 // to have it eliminated.
1760 if (const auto *PrecedingCI = dyn_cast<CastInst>(Val: CastSrc))
1761 if (isEliminableCastPair(CI1: PrecedingCI, CI2: CI))
1762 return false;
1763
1764 return true;
1765}
1766
1767/// Fold {and,or,xor} (cast X), C.
1768static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1769 InstCombinerImpl &IC) {
1770 Constant *C = dyn_cast<Constant>(Val: Logic.getOperand(i_nocapture: 1));
1771 if (!C)
1772 return nullptr;
1773
1774 auto LogicOpc = Logic.getOpcode();
1775 Type *DestTy = Logic.getType();
1776 Type *SrcTy = Cast->getSrcTy();
1777
1778 // Move the logic operation ahead of a zext or sext if the constant is
1779 // unchanged in the smaller source type. Performing the logic in a smaller
1780 // type may provide more information to later folds, and the smaller logic
1781 // instruction may be cheaper (particularly in the case of vectors).
1782 Value *X;
1783 auto &DL = IC.getDataLayout();
1784 if (match(V: Cast, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))))) {
1785 PreservedCastFlags Flags;
1786 if (Constant *TruncC = getLosslessUnsignedTrunc(C, DestTy: SrcTy, DL, Flags: &Flags)) {
1787 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1788 Value *NewOp = IC.Builder.CreateBinOp(Opc: LogicOpc, LHS: X, RHS: TruncC);
1789 auto *ZExt = new ZExtInst(NewOp, DestTy);
1790 ZExt->setNonNeg(Flags.NNeg);
1791 ZExt->andIRFlags(V: Cast);
1792 return ZExt;
1793 }
1794 }
1795
1796 if (match(V: Cast, P: m_OneUse(SubPattern: m_SExtLike(Op: m_Value(V&: X))))) {
1797 if (Constant *TruncC = getLosslessSignedTrunc(C, DestTy: SrcTy, DL)) {
1798 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1799 Value *NewOp = IC.Builder.CreateBinOp(Opc: LogicOpc, LHS: X, RHS: TruncC);
1800 return new SExtInst(NewOp, DestTy);
1801 }
1802 }
1803
1804 return nullptr;
1805}
1806
1807/// Fold {and,or,xor} (cast X), Y.
1808Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1809 auto LogicOpc = I.getOpcode();
1810 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1811
1812 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1813
1814 // fold bitwise(A >> BW - 1, zext(icmp)) (BW is the scalar bits of the
1815 // type of A)
1816 // -> bitwise(zext(A < 0), zext(icmp))
1817 // -> zext(bitwise(A < 0, icmp))
1818 auto FoldBitwiseICmpZeroWithICmp = [&](Value *Op0,
1819 Value *Op1) -> Instruction * {
1820 Value *A;
1821 bool IsMatched =
1822 match(V: Op0,
1823 P: m_OneUse(SubPattern: m_LShr(
1824 L: m_Value(V&: A),
1825 R: m_SpecificInt(V: Op0->getType()->getScalarSizeInBits() - 1)))) &&
1826 match(V: Op1, P: m_OneUse(SubPattern: m_ZExt(Op: m_ICmp(L: m_Value(), R: m_Value()))));
1827
1828 if (!IsMatched)
1829 return nullptr;
1830
1831 auto *ICmpL =
1832 Builder.CreateICmpSLT(LHS: A, RHS: Constant::getNullValue(Ty: A->getType()));
1833 auto *ICmpR = cast<ZExtInst>(Val: Op1)->getOperand(i_nocapture: 0);
1834 auto *BitwiseOp = Builder.CreateBinOp(Opc: LogicOpc, LHS: ICmpL, RHS: ICmpR);
1835
1836 return new ZExtInst(BitwiseOp, Op0->getType());
1837 };
1838
1839 if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op0, Op1))
1840 return Ret;
1841
1842 if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op1, Op0))
1843 return Ret;
1844
1845 CastInst *Cast0 = dyn_cast<CastInst>(Val: Op0);
1846 if (!Cast0)
1847 return nullptr;
1848
1849 // This must be a cast from an integer or integer vector source type to allow
1850 // transformation of the logic operation to the source type.
1851 Type *DestTy = I.getType();
1852 Type *SrcTy = Cast0->getSrcTy();
1853 if (!SrcTy->isIntOrIntVectorTy())
1854 return nullptr;
1855
1856 if (Instruction *Ret = foldLogicCastConstant(Logic&: I, Cast: Cast0, IC&: *this))
1857 return Ret;
1858
1859 CastInst *Cast1 = dyn_cast<CastInst>(Val: Op1);
1860 if (!Cast1)
1861 return nullptr;
1862
1863 // Both operands of the logic operation are casts. The casts must be the
1864 // same kind for reduction.
1865 Instruction::CastOps CastOpcode = Cast0->getOpcode();
1866 if (CastOpcode != Cast1->getOpcode())
1867 return nullptr;
1868
1869 // Can't fold it profitably if no one of casts has one use.
1870 if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
1871 return nullptr;
1872
1873 Value *X, *Y;
1874 if (match(V: Cast0, P: m_ZExtOrSExt(Op: m_Value(V&: X))) &&
1875 match(V: Cast1, P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
1876 // Cast the narrower source to the wider source type.
1877 unsigned XNumBits = X->getType()->getScalarSizeInBits();
1878 unsigned YNumBits = Y->getType()->getScalarSizeInBits();
1879 if (XNumBits != YNumBits) {
1880 // Cast the narrower source to the wider source type only if both of casts
1881 // have one use to avoid creating an extra instruction.
1882 if (!Cast0->hasOneUse() || !Cast1->hasOneUse())
1883 return nullptr;
1884
1885 // If the source types do not match, but the casts are matching extends,
1886 // we can still narrow the logic op.
1887 if (XNumBits < YNumBits) {
1888 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: Y->getType());
1889 } else if (YNumBits < XNumBits) {
1890 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: X->getType());
1891 }
1892 }
1893
1894 // Do the logic op in the intermediate width, then widen more.
1895 Value *NarrowLogic = Builder.CreateBinOp(Opc: LogicOpc, LHS: X, RHS: Y, Name: I.getName());
1896 auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Val: &I);
1897 auto *NewDisjoint = dyn_cast<PossiblyDisjointInst>(Val: NarrowLogic);
1898 if (Disjoint && NewDisjoint)
1899 NewDisjoint->setIsDisjoint(Disjoint->isDisjoint());
1900 return CastInst::Create(CastOpcode, S: NarrowLogic, Ty: DestTy);
1901 }
1902
1903 // If the src type of casts are different, give up for other cast opcodes.
1904 if (SrcTy != Cast1->getSrcTy())
1905 return nullptr;
1906
1907 Value *Cast0Src = Cast0->getOperand(i_nocapture: 0);
1908 Value *Cast1Src = Cast1->getOperand(i_nocapture: 0);
1909
1910 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1911 if (shouldOptimizeCast(CI: Cast0) && shouldOptimizeCast(CI: Cast1)) {
1912 Value *NewOp = Builder.CreateBinOp(Opc: LogicOpc, LHS: Cast0Src, RHS: Cast1Src,
1913 Name: I.getName());
1914 auto *NewCast = CastInst::Create(CastOpcode, S: NewOp, Ty: DestTy);
1915 if (auto *NewTrunc = dyn_cast<TruncInst>(Val: NewCast)) {
1916 auto *Trunc0 = cast<TruncInst>(Val: Cast0);
1917 auto *Trunc1 = cast<TruncInst>(Val: Cast1);
1918 NewTrunc->setHasNoUnsignedWrap(
1919 LogicOpc == Instruction::And
1920 ? Trunc0->hasNoUnsignedWrap() || Trunc1->hasNoUnsignedWrap()
1921 : Trunc0->hasNoUnsignedWrap() && Trunc1->hasNoUnsignedWrap());
1922 NewTrunc->setHasNoSignedWrap(Trunc0->hasNoSignedWrap() &&
1923 Trunc1->hasNoSignedWrap());
1924 }
1925 return NewCast;
1926 }
1927
1928 return nullptr;
1929}
1930
1931static Instruction *foldAndToXor(BinaryOperator &I,
1932 InstCombiner::BuilderTy &Builder) {
1933 assert(I.getOpcode() == Instruction::And);
1934 Value *Op0 = I.getOperand(i_nocapture: 0);
1935 Value *Op1 = I.getOperand(i_nocapture: 1);
1936 Value *A, *B;
1937
1938 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1939 // (A | B) & ~(A & B) --> A ^ B
1940 // (A | B) & ~(B & A) --> A ^ B
1941 if (match(V: &I, P: m_BinOp(L: m_Or(L: m_Value(V&: A), R: m_Value(V&: B)),
1942 R: m_Not(V: m_c_And(L: m_Deferred(V: A), R: m_Deferred(V: B))))))
1943 return BinaryOperator::CreateXor(V1: A, V2: B);
1944
1945 // (A | ~B) & (~A | B) --> ~(A ^ B)
1946 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1947 // (~B | A) & (~A | B) --> ~(A ^ B)
1948 // (~B | A) & (B | ~A) --> ~(A ^ B)
1949 if (Op0->hasOneUse() || Op1->hasOneUse())
1950 if (match(V: &I, P: m_BinOp(L: m_c_Or(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B))),
1951 R: m_c_Or(L: m_Not(V: m_Deferred(V: A)), R: m_Deferred(V: B)))))
1952 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
1953
1954 return nullptr;
1955}
1956
1957static Instruction *foldOrToXor(BinaryOperator &I,
1958 InstCombiner::BuilderTy &Builder) {
1959 assert(I.getOpcode() == Instruction::Or);
1960 Value *Op0 = I.getOperand(i_nocapture: 0);
1961 Value *Op1 = I.getOperand(i_nocapture: 1);
1962 Value *A, *B;
1963
1964 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1965 // (A & B) | ~(A | B) --> ~(A ^ B)
1966 // (A & B) | ~(B | A) --> ~(A ^ B)
1967 if (Op0->hasOneUse() || Op1->hasOneUse())
1968 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
1969 match(V: Op1, P: m_Not(V: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B)))))
1970 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
1971
1972 // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1973 // (A ^ B) | ~(A | B) --> ~(A & B)
1974 // (A ^ B) | ~(B | A) --> ~(A & B)
1975 if (Op0->hasOneUse() || Op1->hasOneUse())
1976 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
1977 match(V: Op1, P: m_Not(V: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B)))))
1978 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: A, RHS: B));
1979
1980 // (A & ~B) | (~A & B) --> A ^ B
1981 // (A & ~B) | (B & ~A) --> A ^ B
1982 // (~B & A) | (~A & B) --> A ^ B
1983 // (~B & A) | (B & ~A) --> A ^ B
1984 if (match(V: Op0, P: m_c_And(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B)))) &&
1985 match(V: Op1, P: m_c_And(L: m_Not(V: m_Specific(V: A)), R: m_Specific(V: B))))
1986 return BinaryOperator::CreateXor(V1: A, V2: B);
1987
1988 return nullptr;
1989}
1990
1991/// Return true if a constant shift amount is always less than the specified
1992/// bit-width. If not, the shift could create poison in the narrower type.
1993static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1994 APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1995 return match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_ULT, Threshold));
1996}
1997
1998/// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1999/// a common zext operand: and (binop (zext X), C), (zext X).
2000Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
2001 // This transform could also apply to {or, and, xor}, but there are better
2002 // folds for those cases, so we don't expect those patterns here. AShr is not
2003 // handled because it should always be transformed to LShr in this sequence.
2004 // The subtract transform is different because it has a constant on the left.
2005 // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
2006 Value *Op0 = And.getOperand(i_nocapture: 0), *Op1 = And.getOperand(i_nocapture: 1);
2007 Constant *C;
2008 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Specific(V: Op1), R: m_Constant(C)))) &&
2009 !match(V: Op0, P: m_OneUse(SubPattern: m_Mul(L: m_Specific(V: Op1), R: m_Constant(C)))) &&
2010 !match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Specific(V: Op1), R: m_Constant(C)))) &&
2011 !match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Specific(V: Op1), R: m_Constant(C)))) &&
2012 !match(V: Op0, P: m_OneUse(SubPattern: m_Sub(L: m_Constant(C), R: m_Specific(V: Op1)))))
2013 return nullptr;
2014
2015 Value *X;
2016 if (!match(V: Op1, P: m_ZExt(Op: m_Value(V&: X))) || Op1->hasNUsesOrMore(N: 3))
2017 return nullptr;
2018
2019 Type *Ty = And.getType();
2020 if (!isa<VectorType>(Val: Ty) && !shouldChangeType(From: Ty, To: X->getType()))
2021 return nullptr;
2022
2023 // If we're narrowing a shift, the shift amount must be safe (less than the
2024 // width) in the narrower type. If the shift amount is greater, instsimplify
2025 // usually handles that case, but we can't guarantee/assert it.
2026 Instruction::BinaryOps Opc = cast<BinaryOperator>(Val: Op0)->getOpcode();
2027 if (Opc == Instruction::LShr || Opc == Instruction::Shl)
2028 if (!canNarrowShiftAmt(C, BitWidth: X->getType()->getScalarSizeInBits()))
2029 return nullptr;
2030
2031 // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
2032 // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
2033 Value *NewC = ConstantExpr::getTrunc(C, Ty: X->getType());
2034 Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, LHS: NewC, RHS: X)
2035 : Builder.CreateBinOp(Opc, LHS: X, RHS: NewC);
2036 return new ZExtInst(Builder.CreateAnd(LHS: NewBO, RHS: X), Ty);
2037}
2038
2039/// Try folding relatively complex patterns for both And and Or operations
2040/// with all And and Or swapped.
2041static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
2042 InstCombiner::BuilderTy &Builder) {
2043 const Instruction::BinaryOps Opcode = I.getOpcode();
2044 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
2045
2046 // Flip the logic operation.
2047 const Instruction::BinaryOps FlippedOpcode =
2048 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
2049
2050 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2051 Value *A, *B, *C, *X, *Y, *Dummy;
2052
2053 // Match following expressions:
2054 // (~(A | B) & C)
2055 // (~(A & B) | C)
2056 // Captures X = ~(A | B) or ~(A & B)
2057 const auto matchNotOrAnd =
2058 [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
2059 Value *&X, bool CountUses = false) -> bool {
2060 if (CountUses && !Op->hasOneUse())
2061 return false;
2062
2063 if (match(Op,
2064 m_c_BinOp(FlippedOpcode,
2065 m_Value(X, m_Not(m_c_BinOp(Opcode, m_A, m_B))), m_C)))
2066 return !CountUses || X->hasOneUse();
2067
2068 return false;
2069 };
2070
2071 // (~(A | B) & C) | ... --> ...
2072 // (~(A & B) | C) & ... --> ...
2073 // TODO: One use checks are conservative. We just need to check that a total
2074 // number of multiple used values does not exceed reduction
2075 // in operations.
2076 if (matchNotOrAnd(Op0, m_Value(V&: A), m_Value(V&: B), m_Value(V&: C), X)) {
2077 // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
2078 // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
2079 if (matchNotOrAnd(Op1, m_Specific(V: A), m_Specific(V: C), m_Specific(V: B), Dummy,
2080 true)) {
2081 Value *Xor = Builder.CreateXor(LHS: B, RHS: C);
2082 return (Opcode == Instruction::Or)
2083 ? BinaryOperator::CreateAnd(V1: Xor, V2: Builder.CreateNot(V: A))
2084 : BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: Xor, RHS: A));
2085 }
2086
2087 // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
2088 // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
2089 if (matchNotOrAnd(Op1, m_Specific(V: B), m_Specific(V: C), m_Specific(V: A), Dummy,
2090 true)) {
2091 Value *Xor = Builder.CreateXor(LHS: A, RHS: C);
2092 return (Opcode == Instruction::Or)
2093 ? BinaryOperator::CreateAnd(V1: Xor, V2: Builder.CreateNot(V: B))
2094 : BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: Xor, RHS: B));
2095 }
2096
2097 // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
2098 // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
2099 if (match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_OneUse(
2100 SubPattern: m_c_BinOp(Opcode, L: m_Specific(V: A), R: m_Specific(V: C)))))))
2101 return BinaryOperator::CreateNot(Op: Builder.CreateBinOp(
2102 Opc: Opcode, LHS: Builder.CreateBinOp(Opc: FlippedOpcode, LHS: B, RHS: C), RHS: A));
2103
2104 // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
2105 // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
2106 if (match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_OneUse(
2107 SubPattern: m_c_BinOp(Opcode, L: m_Specific(V: B), R: m_Specific(V: C)))))))
2108 return BinaryOperator::CreateNot(Op: Builder.CreateBinOp(
2109 Opc: Opcode, LHS: Builder.CreateBinOp(Opc: FlippedOpcode, LHS: A, RHS: C), RHS: B));
2110
2111 // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
2112 // Note, the pattern with swapped and/or is not handled because the
2113 // result is more undefined than a source:
2114 // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
2115 if (Opcode == Instruction::Or && Op0->hasOneUse() &&
2116 match(V: Op1,
2117 P: m_OneUse(SubPattern: m_Not(V: m_Value(
2118 V&: Y, P: m_c_BinOp(Opcode, L: m_Specific(V: C),
2119 R: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B)))))))) {
2120 // X = ~(A | B)
2121 // Y = (C | (A ^ B)
2122 Value *Or = cast<BinaryOperator>(Val: X)->getOperand(i_nocapture: 0);
2123 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: Or, RHS: Y));
2124 }
2125 }
2126
2127 // (~A & B & C) | ... --> ...
2128 // (~A | B | C) | ... --> ...
2129 // TODO: One use checks are conservative. We just need to check that a total
2130 // number of multiple used values does not exceed reduction
2131 // in operations.
2132 if (match(V: Op0,
2133 P: m_OneUse(SubPattern: m_c_BinOp(Opcode: FlippedOpcode,
2134 L: m_BinOp(Opcode: FlippedOpcode, L: m_Value(V&: B), R: m_Value(V&: C)),
2135 R: m_Value(V&: X, P: m_Not(V: m_Value(V&: A)))))) ||
2136 match(V: Op0, P: m_OneUse(SubPattern: m_c_BinOp(Opcode: FlippedOpcode,
2137 L: m_c_BinOp(Opcode: FlippedOpcode, L: m_Value(V&: C),
2138 R: m_Value(V&: X, P: m_Not(V: m_Value(V&: A)))),
2139 R: m_Value(V&: B))))) {
2140 // X = ~A
2141 // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
2142 // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
2143 if (match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_c_BinOp(
2144 Opcode, L: m_c_BinOp(Opcode, L: m_Specific(V: A), R: m_Specific(V: B)),
2145 R: m_Specific(V: C))))) ||
2146 match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_c_BinOp(
2147 Opcode, L: m_c_BinOp(Opcode, L: m_Specific(V: B), R: m_Specific(V: C)),
2148 R: m_Specific(V: A))))) ||
2149 match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_c_BinOp(
2150 Opcode, L: m_c_BinOp(Opcode, L: m_Specific(V: A), R: m_Specific(V: C)),
2151 R: m_Specific(V: B)))))) {
2152 Value *Xor = Builder.CreateXor(LHS: B, RHS: C);
2153 return (Opcode == Instruction::Or)
2154 ? BinaryOperator::CreateNot(Op: Builder.CreateOr(LHS: Xor, RHS: A))
2155 : BinaryOperator::CreateOr(V1: Xor, V2: X);
2156 }
2157
2158 // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
2159 // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
2160 if (match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_OneUse(
2161 SubPattern: m_c_BinOp(Opcode, L: m_Specific(V: A), R: m_Specific(V: B)))))))
2162 return BinaryOperator::Create(
2163 Op: FlippedOpcode, S1: Builder.CreateBinOp(Opc: Opcode, LHS: C, RHS: Builder.CreateNot(V: B)),
2164 S2: X);
2165
2166 // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
2167 // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
2168 if (match(V: Op1, P: m_OneUse(SubPattern: m_Not(V: m_OneUse(
2169 SubPattern: m_c_BinOp(Opcode, L: m_Specific(V: A), R: m_Specific(V: C)))))))
2170 return BinaryOperator::Create(
2171 Op: FlippedOpcode, S1: Builder.CreateBinOp(Opc: Opcode, LHS: B, RHS: Builder.CreateNot(V: C)),
2172 S2: X);
2173 }
2174
2175 return nullptr;
2176}
2177
2178/// Try to reassociate a pair of binops so that values with one use only are
2179/// part of the same instruction. This may enable folds that are limited with
2180/// multi-use restrictions and makes it more likely to match other patterns that
2181/// are looking for a common operand.
2182static Instruction *reassociateForUses(BinaryOperator &BO,
2183 InstCombinerImpl::BuilderTy &Builder) {
2184 Instruction::BinaryOps Opcode = BO.getOpcode();
2185 Value *X, *Y, *Z;
2186 if (match(V: &BO,
2187 P: m_c_BinOp(Opcode, L: m_OneUse(SubPattern: m_BinOp(Opcode, L: m_Value(V&: X), R: m_Value(V&: Y))),
2188 R: m_OneUse(SubPattern: m_Value(V&: Z))))) {
2189 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y) && !isa<Constant>(Val: Z)) {
2190 // (X op Y) op Z --> (Y op Z) op X
2191 if (!X->hasOneUse()) {
2192 Value *YZ = Builder.CreateBinOp(Opc: Opcode, LHS: Y, RHS: Z);
2193 return BinaryOperator::Create(Op: Opcode, S1: YZ, S2: X);
2194 }
2195 // (X op Y) op Z --> (X op Z) op Y
2196 if (!Y->hasOneUse()) {
2197 Value *XZ = Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Z);
2198 return BinaryOperator::Create(Op: Opcode, S1: XZ, S2: Y);
2199 }
2200 }
2201 }
2202
2203 return nullptr;
2204}
2205
2206// Match
2207// (X + C2) | C
2208// (X + C2) ^ C
2209// (X + C2) & C
2210// and convert to do the bitwise logic first:
2211// (X | C) + C2
2212// (X ^ C) + C2
2213// (X & C) + C2
2214// iff bits affected by logic op are lower than last bit affected by math op
2215static Instruction *canonicalizeLogicFirst(BinaryOperator &I,
2216 InstCombiner::BuilderTy &Builder) {
2217 Type *Ty = I.getType();
2218 Instruction::BinaryOps OpC = I.getOpcode();
2219 Value *Op0 = I.getOperand(i_nocapture: 0);
2220 Value *Op1 = I.getOperand(i_nocapture: 1);
2221 Value *X;
2222 const APInt *C, *C2;
2223
2224 if (!(match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C2)))) &&
2225 match(V: Op1, P: m_APInt(Res&: C))))
2226 return nullptr;
2227
2228 unsigned Width = Ty->getScalarSizeInBits();
2229 unsigned LastOneMath = Width - C2->countr_zero();
2230
2231 switch (OpC) {
2232 case Instruction::And:
2233 if (C->countl_one() < LastOneMath)
2234 return nullptr;
2235 break;
2236 case Instruction::Xor:
2237 case Instruction::Or:
2238 if (C->countl_zero() < LastOneMath)
2239 return nullptr;
2240 break;
2241 default:
2242 llvm_unreachable("Unexpected BinaryOp!");
2243 }
2244
2245 Value *NewBinOp = Builder.CreateBinOp(Opc: OpC, LHS: X, RHS: ConstantInt::get(Ty, V: *C));
2246 return BinaryOperator::CreateWithCopiedFlags(Opc: Instruction::Add, V1: NewBinOp,
2247 V2: ConstantInt::get(Ty, V: *C2), CopyO: Op0);
2248}
2249
2250// binop(shift(ShiftedC1, ShAmt), shift(ShiftedC2, add(ShAmt, AddC))) ->
2251// shift(binop(ShiftedC1, shift(ShiftedC2, AddC)), ShAmt)
2252// where both shifts are the same and AddC is a valid shift amount.
2253Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
2254 assert((I.isBitwiseLogicOp() || I.getOpcode() == Instruction::Add) &&
2255 "Unexpected opcode");
2256
2257 Value *ShAmt;
2258 Constant *ShiftedC1, *ShiftedC2, *AddC;
2259 Type *Ty = I.getType();
2260 unsigned BitWidth = Ty->getScalarSizeInBits();
2261 if (!match(V: &I, P: m_c_BinOp(L: m_Shift(L: m_ImmConstant(C&: ShiftedC1), R: m_Value(V&: ShAmt)),
2262 R: m_Shift(L: m_ImmConstant(C&: ShiftedC2),
2263 R: m_AddLike(L: m_Deferred(V: ShAmt),
2264 R: m_ImmConstant(C&: AddC))))))
2265 return nullptr;
2266
2267 // Make sure the add constant is a valid shift amount.
2268 if (!match(V: AddC,
2269 P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_ULT, Threshold: APInt(BitWidth, BitWidth))))
2270 return nullptr;
2271
2272 // Avoid constant expressions.
2273 auto *Op0Inst = dyn_cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
2274 auto *Op1Inst = dyn_cast<Instruction>(Val: I.getOperand(i_nocapture: 1));
2275 if (!Op0Inst || !Op1Inst)
2276 return nullptr;
2277
2278 // Both shifts must be the same.
2279 Instruction::BinaryOps ShiftOp =
2280 static_cast<Instruction::BinaryOps>(Op0Inst->getOpcode());
2281 if (ShiftOp != Op1Inst->getOpcode())
2282 return nullptr;
2283
2284 // For adds, only left shifts are supported.
2285 if (I.getOpcode() == Instruction::Add && ShiftOp != Instruction::Shl)
2286 return nullptr;
2287
2288 Value *NewC = Builder.CreateBinOp(
2289 Opc: I.getOpcode(), LHS: ShiftedC1, RHS: Builder.CreateBinOp(Opc: ShiftOp, LHS: ShiftedC2, RHS: AddC));
2290 return BinaryOperator::Create(Op: ShiftOp, S1: NewC, S2: ShAmt);
2291}
2292
2293// Fold and/or/xor with two equal intrinsic IDs:
2294// bitwise(fshl (A, B, ShAmt), fshl(C, D, ShAmt))
2295// -> fshl(bitwise(A, C), bitwise(B, D), ShAmt)
2296// bitwise(fshr (A, B, ShAmt), fshr(C, D, ShAmt))
2297// -> fshr(bitwise(A, C), bitwise(B, D), ShAmt)
2298// bitwise(bswap(A), bswap(B)) -> bswap(bitwise(A, B))
2299// bitwise(bswap(A), C) -> bswap(bitwise(A, bswap(C)))
2300// bitwise(bitreverse(A), bitreverse(B)) -> bitreverse(bitwise(A, B))
2301// bitwise(bitreverse(A), C) -> bitreverse(bitwise(A, bitreverse(C)))
2302static Instruction *
2303foldBitwiseLogicWithIntrinsics(BinaryOperator &I,
2304 InstCombiner::BuilderTy &Builder) {
2305 assert(I.isBitwiseLogicOp() && "Should and/or/xor");
2306 if (!I.getOperand(i_nocapture: 0)->hasOneUse())
2307 return nullptr;
2308 IntrinsicInst *X = dyn_cast<IntrinsicInst>(Val: I.getOperand(i_nocapture: 0));
2309 if (!X)
2310 return nullptr;
2311
2312 IntrinsicInst *Y = dyn_cast<IntrinsicInst>(Val: I.getOperand(i_nocapture: 1));
2313 if (Y && (!Y->hasOneUse() || X->getIntrinsicID() != Y->getIntrinsicID()))
2314 return nullptr;
2315
2316 Intrinsic::ID IID = X->getIntrinsicID();
2317 const APInt *RHSC;
2318 // Try to match constant RHS.
2319 if (!Y && (!(IID == Intrinsic::bswap || IID == Intrinsic::bitreverse) ||
2320 !match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHSC))))
2321 return nullptr;
2322
2323 switch (IID) {
2324 case Intrinsic::fshl:
2325 case Intrinsic::fshr: {
2326 if (X->getOperand(i_nocapture: 2) != Y->getOperand(i_nocapture: 2))
2327 return nullptr;
2328 Value *NewOp0 =
2329 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: X->getOperand(i_nocapture: 0), RHS: Y->getOperand(i_nocapture: 0));
2330 Value *NewOp1 =
2331 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: X->getOperand(i_nocapture: 1), RHS: Y->getOperand(i_nocapture: 1));
2332 Function *F =
2333 Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: IID, OverloadTys: I.getType());
2334 return CallInst::Create(Func: F, Args: {NewOp0, NewOp1, X->getOperand(i_nocapture: 2)});
2335 }
2336 case Intrinsic::bswap:
2337 case Intrinsic::bitreverse: {
2338 Value *NewOp0 = Builder.CreateBinOp(
2339 Opc: I.getOpcode(), LHS: X->getOperand(i_nocapture: 0),
2340 RHS: Y ? Y->getOperand(i_nocapture: 0)
2341 : ConstantInt::get(Ty: I.getType(), V: IID == Intrinsic::bswap
2342 ? RHSC->byteSwap()
2343 : RHSC->reverseBits()));
2344 Function *F =
2345 Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: IID, OverloadTys: I.getType());
2346 return CallInst::Create(Func: F, Args: {NewOp0});
2347 }
2348 default:
2349 return nullptr;
2350 }
2351}
2352
2353// Try to simplify V by replacing occurrences of Op with RepOp, but only look
2354// through bitwise operations. In particular, for X | Y we try to replace Y with
2355// 0 inside X and for X & Y we try to replace Y with -1 inside X.
2356// Return the simplified result of X if successful, and nullptr otherwise.
2357// If SimplifyOnly is true, no new instructions will be created.
2358static Value *simplifyAndOrWithOpReplaced(Value *V, Value *Op, Value *RepOp,
2359 bool SimplifyOnly,
2360 InstCombinerImpl &IC,
2361 unsigned Depth = 0) {
2362 if (Op == RepOp)
2363 return nullptr;
2364
2365 if (V == Op)
2366 return RepOp;
2367
2368 auto *I = dyn_cast<BinaryOperator>(Val: V);
2369 if (!I || !I->isBitwiseLogicOp() || Depth >= 3)
2370 return nullptr;
2371
2372 if (!I->hasOneUse())
2373 SimplifyOnly = true;
2374
2375 Value *NewOp0 = simplifyAndOrWithOpReplaced(V: I->getOperand(i_nocapture: 0), Op, RepOp,
2376 SimplifyOnly, IC, Depth: Depth + 1);
2377 Value *NewOp1 = simplifyAndOrWithOpReplaced(V: I->getOperand(i_nocapture: 1), Op, RepOp,
2378 SimplifyOnly, IC, Depth: Depth + 1);
2379 if (!NewOp0 && !NewOp1)
2380 return nullptr;
2381
2382 if (!NewOp0)
2383 NewOp0 = I->getOperand(i_nocapture: 0);
2384 if (!NewOp1)
2385 NewOp1 = I->getOperand(i_nocapture: 1);
2386
2387 if (Value *Res = simplifyBinOp(Opcode: I->getOpcode(), LHS: NewOp0, RHS: NewOp1,
2388 Q: IC.getSimplifyQuery().getWithInstruction(I)))
2389 return Res;
2390
2391 if (SimplifyOnly)
2392 return nullptr;
2393 return IC.Builder.CreateBinOp(Opc: I->getOpcode(), LHS: NewOp0, RHS: NewOp1);
2394}
2395
2396/// The pattern div_ceil(X, P) * P, where P is a power of 2, lowers to the
2397/// following conditional round-up: (X + select(C, 0, Pow2)) & -Pow2, where
2398/// C is X % Pow2 == 0. This may be simplified to (X + (Pow2-1)) & -Pow2.
2399static Instruction *
2400foldRoundUpToPow2Alignment(BinaryOperator &I,
2401 InstCombiner::BuilderTy &Builder) {
2402 const APInt *NegP;
2403 Value *Add;
2404 if (!match(V: &I, P: m_And(L: m_Value(V&: Add), R: m_NegatedPower2(V&: NegP))))
2405 return nullptr;
2406
2407 Value *X, *Cond;
2408 APInt Mask = ~*NegP;
2409
2410 // Match the pattern. Ensure the true arm of the select is zero, and the false
2411 // one is the Pow2.
2412 if (!match(V: Add,
2413 P: m_OneUse(SubPattern: m_c_Add(L: m_Value(V&: X), R: m_Select(C: m_Value(V&: Cond), L: m_ZeroInt(),
2414 R: m_SpecificInt(V: -*NegP))))))
2415 return nullptr;
2416
2417 // icmp ne should have already been canonicalized to the eq form for this
2418 // pattern.
2419 if (!match(V: Cond, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
2420 L: m_And(L: m_Specific(V: X), R: m_SpecificInt(V: Mask)),
2421 R: m_Zero())))
2422 return nullptr;
2423
2424 Type *Ty = I.getType();
2425 Value *NewAdd = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: Mask));
2426 return BinaryOperator::CreateAnd(V1: NewAdd, V2: ConstantInt::get(Ty, V: *NegP));
2427}
2428
2429/// Reassociate and/or expressions to see if we can fold the inner and/or ops.
2430/// TODO: Make this recursive; it's a little tricky because an arbitrary
2431/// number of and/or instructions might have to be created.
2432Value *InstCombinerImpl::reassociateBooleanAndOr(Value *LHS, Value *X, Value *Y,
2433 Instruction &I, bool IsAnd,
2434 bool RHSIsLogical) {
2435 Instruction::BinaryOps Opcode = IsAnd ? Instruction::And : Instruction::Or;
2436 Value *Folded = nullptr;
2437 // LHS bop (X lop Y) --> (LHS bop X) lop Y
2438 // LHS bop (X bop Y) --> (LHS bop X) bop Y
2439 if (Value *Res = foldBooleanAndOr(LHS, RHS: X, I, IsAnd, /*IsLogical=*/false))
2440 Folded = RHSIsLogical ? Builder.CreateLogicalOp(Opc: Opcode, Cond1: Res, Cond2: Y)
2441 : Builder.CreateBinOp(Opc: Opcode, LHS: Res, RHS: Y);
2442 // LHS bop (X bop Y) --> X bop (LHS bop Y)
2443 // LHS bop (X lop Y) --> X lop (LHS bop Y)
2444 else if (Value *Res = foldBooleanAndOr(LHS, RHS: Y, I, IsAnd, /*IsLogical=*/false))
2445 Folded = RHSIsLogical ? Builder.CreateLogicalOp(Opc: Opcode, Cond1: X, Cond2: Res)
2446 : Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Res);
2447 if (SelectInst *SI = dyn_cast_or_null<SelectInst>(Val: Folded);
2448 SI != nullptr && !ProfcheckDisableMetadataFixes)
2449 // If the bop I was originally a lop, we could recover branch weight
2450 // information using that lop's weights. However, InstCombine usually
2451 // replaces the lop with a bop by the time we get here, deleting the branch
2452 // weight information. Therefore, we can only assume unknown branch weights.
2453 // TODO: see if it's possible to recover branch weight information from the
2454 // original lop (https://github.com/llvm/llvm-project/issues/183864).
2455 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE,
2456 F: I.getFunction());
2457 return Folded;
2458}
2459
2460// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2461// here. We should standardize that construct where it is needed or choose some
2462// other way to ensure that commutated variants of patterns are not missed.
2463Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
2464 Type *Ty = I.getType();
2465
2466 if (Value *V = simplifyAndInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2467 Q: SQ.getWithInstruction(I: &I)))
2468 return replaceInstUsesWith(I, V);
2469
2470 if (SimplifyAssociativeOrCommutative(I))
2471 return &I;
2472
2473 if (Instruction *X = foldVectorBinop(Inst&: I))
2474 return X;
2475
2476 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2477 return Phi;
2478
2479 // See if we can simplify any instructions used by the instruction whose sole
2480 // purpose is to compute bits we don't care about.
2481 if (SimplifyDemandedInstructionBits(Inst&: I))
2482 return &I;
2483
2484 // Do this before using distributive laws to catch simple and/or/not patterns.
2485 if (Instruction *Xor = foldAndToXor(I, Builder))
2486 return Xor;
2487
2488 if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
2489 return X;
2490
2491 // (A|B)&(A|C) -> A|(B&C) etc
2492 if (Value *V = foldUsingDistributiveLaws(I))
2493 return replaceInstUsesWith(I, V);
2494
2495 if (Instruction *R = foldBinOpShiftWithShift(I))
2496 return R;
2497
2498 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2499
2500 Value *X, *Y;
2501 const APInt *C;
2502 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LogicalShift(L: m_One(), R: m_Value(V&: X)))) ||
2503 (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_APInt(Res&: C), R: m_Value(V&: X)))) && (*C)[0])) &&
2504 match(V: Op1, P: m_One())) {
2505 // (1 >> X) & 1 --> zext(X == 0)
2506 // (C << X) & 1 --> zext(X == 0), when C is odd
2507 Value *IsZero = Builder.CreateICmpEQ(LHS: X, RHS: ConstantInt::get(Ty, V: 0));
2508 return new ZExtInst(IsZero, Ty);
2509 }
2510
2511 // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
2512 Value *Neg;
2513 if (match(V: &I,
2514 P: m_c_And(L: m_Value(V&: Neg, P: m_OneUse(SubPattern: m_Neg(V: m_And(L: m_Value(), R: m_One())))),
2515 R: m_Value(V&: Y)))) {
2516 Value *Cmp = Builder.CreateIsNull(Arg: Neg);
2517 return createSelectInstWithUnknownProfile(C: Cmp,
2518 S1: ConstantInt::getNullValue(Ty), S2: Y);
2519 }
2520
2521 // Canonicalize:
2522 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2.
2523 if (match(V: &I, P: m_c_And(L: m_Value(V&: Y), R: m_OneUse(SubPattern: m_CombineOr(
2524 Ps: m_c_Add(L: m_Value(V&: X), R: m_Deferred(V: Y)),
2525 Ps: m_Sub(L: m_Value(V&: X), R: m_Deferred(V: Y)))))) &&
2526 isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CxtI: &I))
2527 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: X), V2: Y);
2528
2529 if (match(V: Op1, P: m_APInt(Res&: C))) {
2530 const APInt *XorC;
2531 if (match(V: Op0, P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: X), R: m_APInt(Res&: XorC))))) {
2532 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2533 Constant *NewC = ConstantInt::get(Ty, V: *C & *XorC);
2534 Value *And = Builder.CreateAnd(LHS: X, RHS: Op1);
2535 And->takeName(V: Op0);
2536 return BinaryOperator::CreateXor(V1: And, V2: NewC);
2537 }
2538
2539 const APInt *OrC;
2540 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC))))) {
2541 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
2542 // NOTE: This reduces the number of bits set in the & mask, which
2543 // can expose opportunities for store narrowing for scalars.
2544 // NOTE: SimplifyDemandedBits should have already removed bits from C1
2545 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
2546 // above, but this feels safer.
2547 APInt Together = *C & *OrC;
2548 Value *And = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty, V: Together ^ *C));
2549 And->takeName(V: Op0);
2550 return BinaryOperator::CreateOr(V1: And, V2: ConstantInt::get(Ty, V: Together));
2551 }
2552
2553 unsigned Width = Ty->getScalarSizeInBits();
2554 const APInt *ShiftC;
2555 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExt(Op: m_AShr(L: m_Value(V&: X), R: m_APInt(Res&: ShiftC))))) &&
2556 ShiftC->ult(RHS: Width)) {
2557 if (*C == APInt::getLowBitsSet(numBits: Width, loBitsSet: Width - ShiftC->getZExtValue())) {
2558 // We are clearing high bits that were potentially set by sext+ashr:
2559 // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
2560 Value *Sext = Builder.CreateSExt(V: X, DestTy: Ty);
2561 Constant *ShAmtC = ConstantInt::get(Ty, V: ShiftC->zext(width: Width));
2562 return BinaryOperator::CreateLShr(V1: Sext, V2: ShAmtC);
2563 }
2564 }
2565
2566 // If this 'and' clears the sign-bits added by ashr, replace with lshr:
2567 // and (ashr X, ShiftC), C --> lshr X, ShiftC
2568 if (match(V: Op0, P: m_AShr(L: m_Value(V&: X), R: m_APInt(Res&: ShiftC))) && ShiftC->ult(RHS: Width) &&
2569 C->isMask(numBits: Width - ShiftC->getZExtValue()))
2570 return BinaryOperator::CreateLShr(V1: X, V2: ConstantInt::get(Ty, V: *ShiftC));
2571
2572 const APInt *AddC;
2573 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: AddC)))) {
2574 // If we are masking the result of the add down to exactly one bit and
2575 // the constant we are adding has no bits set below that bit, then the
2576 // add is flipping a single bit. Example:
2577 // (X + 4) & 4 --> (X & 4) ^ 4
2578 if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
2579 assert((*C & *AddC) != 0 && "Expected common bit");
2580 Value *NewAnd = Builder.CreateAnd(LHS: X, RHS: Op1);
2581 return BinaryOperator::CreateXor(V1: NewAnd, V2: Op1);
2582 }
2583 }
2584
2585 // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
2586 // bitwidth of X and OP behaves well when given trunc(C1) and X.
2587 auto isNarrowableBinOpcode = [](BinaryOperator *B) {
2588 switch (B->getOpcode()) {
2589 case Instruction::Xor:
2590 case Instruction::Or:
2591 case Instruction::Mul:
2592 case Instruction::Add:
2593 case Instruction::Sub:
2594 return true;
2595 default:
2596 return false;
2597 }
2598 };
2599 BinaryOperator *BO;
2600 if (match(V: Op0, P: m_OneUse(SubPattern: m_BinOp(I&: BO))) && isNarrowableBinOpcode(BO)) {
2601 Instruction::BinaryOps BOpcode = BO->getOpcode();
2602 Value *X;
2603 const APInt *C1;
2604 // TODO: The one-use restrictions could be relaxed a little if the AND
2605 // is going to be removed.
2606 // Try to narrow the 'and' and a binop with constant operand:
2607 // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
2608 if (match(V: BO, P: m_c_BinOp(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))), R: m_APInt(Res&: C1))) &&
2609 C->isIntN(N: X->getType()->getScalarSizeInBits())) {
2610 unsigned XWidth = X->getType()->getScalarSizeInBits();
2611 Constant *TruncC1 = ConstantInt::get(Ty: X->getType(), V: C1->trunc(width: XWidth));
2612 Value *BinOp = isa<ZExtInst>(Val: BO->getOperand(i_nocapture: 0))
2613 ? Builder.CreateBinOp(Opc: BOpcode, LHS: X, RHS: TruncC1)
2614 : Builder.CreateBinOp(Opc: BOpcode, LHS: TruncC1, RHS: X);
2615 Constant *TruncC = ConstantInt::get(Ty: X->getType(), V: C->trunc(width: XWidth));
2616 Value *And = Builder.CreateAnd(LHS: BinOp, RHS: TruncC);
2617 return new ZExtInst(And, Ty);
2618 }
2619
2620 // Similar to above: if the mask matches the zext input width, then the
2621 // 'and' can be eliminated, so we can truncate the other variable op:
2622 // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
2623 if (isa<Instruction>(Val: BO->getOperand(i_nocapture: 0)) &&
2624 match(V: BO->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) &&
2625 C->isMask(numBits: X->getType()->getScalarSizeInBits())) {
2626 Y = BO->getOperand(i_nocapture: 1);
2627 Value *TrY = Builder.CreateTrunc(V: Y, DestTy: X->getType(), Name: Y->getName() + ".tr");
2628 Value *NewBO =
2629 Builder.CreateBinOp(Opc: BOpcode, LHS: X, RHS: TrY, Name: BO->getName() + ".narrow");
2630 return new ZExtInst(NewBO, Ty);
2631 }
2632 // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
2633 if (isa<Instruction>(Val: BO->getOperand(i_nocapture: 1)) &&
2634 match(V: BO->getOperand(i_nocapture: 1), P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) &&
2635 C->isMask(numBits: X->getType()->getScalarSizeInBits())) {
2636 Y = BO->getOperand(i_nocapture: 0);
2637 Value *TrY = Builder.CreateTrunc(V: Y, DestTy: X->getType(), Name: Y->getName() + ".tr");
2638 Value *NewBO =
2639 Builder.CreateBinOp(Opc: BOpcode, LHS: TrY, RHS: X, Name: BO->getName() + ".narrow");
2640 return new ZExtInst(NewBO, Ty);
2641 }
2642 }
2643
2644 // This is intentionally placed after the narrowing transforms for
2645 // efficiency (transform directly to the narrow logic op if possible).
2646 // If the mask is only needed on one incoming arm, push the 'and' op up.
2647 if (match(V: Op0, P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: X), R: m_Value(V&: Y)))) ||
2648 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2649 APInt NotAndMask(~(*C));
2650 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Val: Op0)->getOpcode();
2651 if (MaskedValueIsZero(V: X, Mask: NotAndMask, CxtI: &I)) {
2652 // Not masking anything out for the LHS, move mask to RHS.
2653 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
2654 Value *NewRHS = Builder.CreateAnd(LHS: Y, RHS: Op1, Name: Y->getName() + ".masked");
2655 return BinaryOperator::Create(Op: BinOp, S1: X, S2: NewRHS);
2656 }
2657 if (!isa<Constant>(Val: Y) && MaskedValueIsZero(V: Y, Mask: NotAndMask, CxtI: &I)) {
2658 // Not masking anything out for the RHS, move mask to LHS.
2659 // and ({x}or X, Y), C --> {x}or (and X, C), Y
2660 Value *NewLHS = Builder.CreateAnd(LHS: X, RHS: Op1, Name: X->getName() + ".masked");
2661 return BinaryOperator::Create(Op: BinOp, S1: NewLHS, S2: Y);
2662 }
2663 }
2664
2665 // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
2666 // constant, test if the shift amount equals the offset bit index:
2667 // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
2668 // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
2669 if (C->isPowerOf2() &&
2670 match(V: Op0, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Power2(V&: ShiftC), R: m_Value(V&: X))))) {
2671 int Log2ShiftC = ShiftC->exactLogBase2();
2672 int Log2C = C->exactLogBase2();
2673 bool IsShiftLeft =
2674 cast<BinaryOperator>(Val: Op0)->getOpcode() == Instruction::Shl;
2675 int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
2676 assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
2677 Value *Cmp = Builder.CreateICmpEQ(LHS: X, RHS: ConstantInt::get(Ty, V: BitNum));
2678 return createSelectInstWithUnknownProfile(C: Cmp, S1: ConstantInt::get(Ty, V: *C),
2679 S2: ConstantInt::getNullValue(Ty));
2680 }
2681
2682 Constant *C1, *C2;
2683 const APInt *C3 = C;
2684 Value *X;
2685 if (C3->isPowerOf2()) {
2686 Constant *Log2C3 = ConstantInt::get(Ty, V: C3->countr_zero());
2687 if (match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Shl(L: m_ImmConstant(C&: C1), R: m_Value(V&: X)),
2688 R: m_ImmConstant(C&: C2)))) &&
2689 match(V: C1, P: m_Power2())) {
2690 Constant *Log2C1 = ConstantExpr::getExactLogBase2(C: C1);
2691 Constant *LshrC = ConstantExpr::getAdd(C1: C2, C2: Log2C3);
2692 KnownBits KnownLShrc = computeKnownBits(V: LshrC, CxtI: nullptr);
2693 if (KnownLShrc.getMaxValue().ult(RHS: Width)) {
2694 // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
2695 // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
2696 Constant *CmpC = ConstantExpr::getSub(C1: LshrC, C2: Log2C1);
2697 Value *Cmp = Builder.CreateICmpEQ(LHS: X, RHS: CmpC);
2698 return createSelectInstWithUnknownProfile(
2699 C: Cmp, S1: ConstantInt::get(Ty, V: *C3), S2: ConstantInt::getNullValue(Ty));
2700 }
2701 }
2702
2703 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_LShr(L: m_ImmConstant(C&: C1), R: m_Value(V&: X)),
2704 R: m_ImmConstant(C&: C2)))) &&
2705 match(V: C1, P: m_Power2())) {
2706 Constant *Log2C1 = ConstantExpr::getExactLogBase2(C: C1);
2707 Constant *Cmp =
2708 ConstantFoldCompareInstOperands(Predicate: ICmpInst::ICMP_ULT, LHS: Log2C3, RHS: C2, DL);
2709 if (Cmp && Cmp->isNullValue()) {
2710 // iff C1,C3 is pow2 and Log2(C3) >= C2:
2711 // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
2712 Constant *ShlC = ConstantExpr::getAdd(C1: C2, C2: Log2C1);
2713 Constant *CmpC = ConstantExpr::getSub(C1: ShlC, C2: Log2C3);
2714 Value *Cmp = Builder.CreateICmpEQ(LHS: X, RHS: CmpC);
2715 return createSelectInstWithUnknownProfile(
2716 C: Cmp, S1: ConstantInt::get(Ty, V: *C3), S2: ConstantInt::getNullValue(Ty));
2717 }
2718 }
2719 }
2720 }
2721
2722 // If we are clearing the sign bit of a floating-point value, convert this to
2723 // fabs, then cast back to integer.
2724 //
2725 // This is a generous interpretation for noimplicitfloat, this is not a true
2726 // floating-point operation.
2727 //
2728 // Assumes any IEEE-represented type has the sign bit in the high bit.
2729 // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
2730 Value *CastOp;
2731 if (match(V: Op0, P: m_ElementWiseBitCast(Op: m_Value(V&: CastOp))) &&
2732 match(V: Op1, P: m_MaxSignedValue()) &&
2733 !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
2734 Kind: Attribute::NoImplicitFloat)) {
2735 Type *EltTy = CastOp->getType()->getScalarType();
2736 if (EltTy->isFloatingPointTy() &&
2737 APFloat::hasSignBitInMSB(EltTy->getFltSemantics())) {
2738 Value *FAbs = Builder.CreateFAbs(V: CastOp);
2739 return new BitCastInst(FAbs, I.getType());
2740 }
2741 }
2742
2743 // and(shl(zext(X), Y), SignMask) -> and(sext(X), SignMask)
2744 // where Y is a valid shift amount.
2745 if (match(V: &I, P: m_And(L: m_OneUse(SubPattern: m_Shl(L: m_ZExt(Op: m_Value(V&: X)), R: m_Value(V&: Y))),
2746 R: m_SignMask())) &&
2747 match(V: Y, P: m_SpecificInt_ICMP(
2748 Predicate: ICmpInst::Predicate::ICMP_EQ,
2749 Threshold: APInt(Ty->getScalarSizeInBits(),
2750 Ty->getScalarSizeInBits() -
2751 X->getType()->getScalarSizeInBits())))) {
2752 auto *SExt = Builder.CreateSExt(V: X, DestTy: Ty, Name: X->getName() + ".signext");
2753 return BinaryOperator::CreateAnd(V1: SExt, V2: Op1);
2754 }
2755
2756 if (Instruction *Z = narrowMaskedBinOp(And&: I))
2757 return Z;
2758
2759 if (I.getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2760 if (auto *SI0 = dyn_cast<SelectInst>(Val: Op0)) {
2761 if (auto *R =
2762 foldAndOrOfSelectUsingImpliedCond(Op: Op1, SI&: *SI0, /* IsAnd */ true))
2763 return R;
2764 }
2765 if (auto *SI1 = dyn_cast<SelectInst>(Val: Op1)) {
2766 if (auto *R =
2767 foldAndOrOfSelectUsingImpliedCond(Op: Op0, SI&: *SI1, /* IsAnd */ true))
2768 return R;
2769 }
2770 }
2771
2772 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2773 return FoldedLogic;
2774
2775 if (Instruction *DeMorgan = matchDeMorgansLaws(I, IC&: *this))
2776 return DeMorgan;
2777
2778 {
2779 Value *A, *B, *C;
2780 // A & ~(A ^ B) --> A & B
2781 if (match(V: Op1, P: m_Not(V: m_c_Xor(L: m_Specific(V: Op0), R: m_Value(V&: B)))))
2782 return BinaryOperator::CreateAnd(V1: Op0, V2: B);
2783 // ~(A ^ B) & A --> A & B
2784 if (match(V: Op0, P: m_Not(V: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: B)))))
2785 return BinaryOperator::CreateAnd(V1: Op1, V2: B);
2786
2787 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
2788 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2789 match(V: Op1, P: m_Xor(L: m_Xor(L: m_Specific(V: B), R: m_Value(V&: C)), R: m_Specific(V: A)))) {
2790 Value *NotC = Op1->hasOneUse()
2791 ? Builder.CreateNot(V: C)
2792 : getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder);
2793 if (NotC != nullptr)
2794 return BinaryOperator::CreateAnd(V1: Op0, V2: NotC);
2795 }
2796
2797 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
2798 if (match(V: Op0, P: m_Xor(L: m_Xor(L: m_Value(V&: A), R: m_Value(V&: C)), R: m_Value(V&: B))) &&
2799 match(V: Op1, P: m_Xor(L: m_Specific(V: B), R: m_Specific(V: A)))) {
2800 Value *NotC = Op0->hasOneUse()
2801 ? Builder.CreateNot(V: C)
2802 : getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder);
2803 if (NotC != nullptr)
2804 return BinaryOperator::CreateAnd(V1: Op1, V2: NotC);
2805 }
2806
2807 // (A | B) & (~A ^ B) -> A & B
2808 // (A | B) & (B ^ ~A) -> A & B
2809 // (B | A) & (~A ^ B) -> A & B
2810 // (B | A) & (B ^ ~A) -> A & B
2811 if (match(V: Op1, P: m_c_Xor(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2812 match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2813 return BinaryOperator::CreateAnd(V1: A, V2: B);
2814
2815 // (~A ^ B) & (A | B) -> A & B
2816 // (~A ^ B) & (B | A) -> A & B
2817 // (B ^ ~A) & (A | B) -> A & B
2818 // (B ^ ~A) & (B | A) -> A & B
2819 if (match(V: Op0, P: m_c_Xor(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2820 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2821 return BinaryOperator::CreateAnd(V1: A, V2: B);
2822
2823 // (~A | B) & (A ^ B) -> ~A & B
2824 // (~A | B) & (B ^ A) -> ~A & B
2825 // (B | ~A) & (A ^ B) -> ~A & B
2826 // (B | ~A) & (B ^ A) -> ~A & B
2827 if (match(V: Op0, P: m_c_Or(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2828 match(V: Op1, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
2829 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
2830
2831 // (A ^ B) & (~A | B) -> ~A & B
2832 // (B ^ A) & (~A | B) -> ~A & B
2833 // (A ^ B) & (B | ~A) -> ~A & B
2834 // (B ^ A) & (B | ~A) -> ~A & B
2835 if (match(V: Op1, P: m_c_Or(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2836 match(V: Op0, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
2837 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
2838 }
2839
2840 if (Value *Res =
2841 foldBooleanAndOr(LHS: Op0, RHS: Op1, I, /*IsAnd=*/true, /*IsLogical=*/false))
2842 return replaceInstUsesWith(I, V: Res);
2843
2844 if (match(V: Op1, P: m_OneUse(SubPattern: m_LogicalAnd(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2845 bool IsLogical = isa<SelectInst>(Val: Op1);
2846 if (auto *V = reassociateBooleanAndOr(LHS: Op0, X, Y, I, /*IsAnd=*/true,
2847 /*RHSIsLogical=*/IsLogical))
2848 return replaceInstUsesWith(I, V);
2849 }
2850 if (match(V: Op0, P: m_OneUse(SubPattern: m_LogicalAnd(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2851 bool IsLogical = isa<SelectInst>(Val: Op0);
2852 if (auto *V = reassociateBooleanAndOr(LHS: Op1, X, Y, I, /*IsAnd=*/true,
2853 /*RHSIsLogical=*/IsLogical))
2854 return replaceInstUsesWith(I, V);
2855 }
2856
2857 if (Instruction *FoldedFCmps = reassociateFCmps(BO&: I, Builder))
2858 return FoldedFCmps;
2859
2860 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
2861 return CastedAnd;
2862
2863 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
2864 return Sel;
2865
2866 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
2867 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
2868 // with binop identity constant. But creating a select with non-constant
2869 // arm may not be reversible due to poison semantics. Is that a good
2870 // canonicalization?
2871 Value *A, *B;
2872 if (match(V: &I, P: m_c_And(L: m_SExt(Op: m_Value(V&: A)), R: m_Value(V&: B))) &&
2873 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
2874 return createSelectInstWithUnknownProfile(C: A, S1: B, S2: Constant::getNullValue(Ty));
2875
2876 // Similarly, a 'not' of the bool translates to a swap of the select arms:
2877 // ~sext(A) & B / B & ~sext(A) --> A ? 0 : B
2878 if (match(V: &I, P: m_c_And(L: m_Not(V: m_SExt(Op: m_Value(V&: A))), R: m_Value(V&: B))) &&
2879 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
2880 return createSelectInstWithUnknownProfile(C: A, S1: Constant::getNullValue(Ty), S2: B);
2881
2882 // and(zext(A), B) -> A ? (B & 1) : 0
2883 if (match(V: &I, P: m_c_And(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: A))), R: m_Value(V&: B))) &&
2884 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
2885 return createSelectInstWithUnknownProfile(
2886 C: A, S1: Builder.CreateAnd(LHS: B, RHS: ConstantInt::get(Ty, V: 1)),
2887 S2: Constant::getNullValue(Ty));
2888
2889 // (-1 + A) & B --> A ? 0 : B where A is 0/1.
2890 if (match(V: &I, P: m_c_And(L: m_OneUse(SubPattern: m_Add(L: m_ZExtOrSelf(Op: m_Value(V&: A)), R: m_AllOnes())),
2891 R: m_Value(V&: B)))) {
2892 if (A->getType()->isIntOrIntVectorTy(BitWidth: 1))
2893 return createSelectInstWithUnknownProfile(C: A, S1: Constant::getNullValue(Ty),
2894 S2: B);
2895 if (computeKnownBits(V: A, CxtI: &I).countMaxActiveBits() <= 1) {
2896 return createSelectInstWithUnknownProfile(
2897 C: Builder.CreateICmpEQ(LHS: A, RHS: Constant::getNullValue(Ty: A->getType())), S1: B,
2898 S2: Constant::getNullValue(Ty));
2899 }
2900 }
2901
2902 // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
2903 if (match(V: &I, P: m_c_And(L: m_OneUse(SubPattern: m_SExtOrSelf(
2904 Op: m_AShr(L: m_Value(V&: X), R: m_APIntAllowPoison(Res&: C)))),
2905 R: m_Value(V&: Y))) &&
2906 *C == X->getType()->getScalarSizeInBits() - 1) {
2907 Value *IsNeg = Builder.CreateIsNeg(Arg: X, Name: "isneg");
2908 return createSelectInstWithUnknownProfile(C: IsNeg, S1: Y,
2909 S2: ConstantInt::getNullValue(Ty));
2910 }
2911 // If there's a 'not' of the shifted value, swap the select operands:
2912 // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
2913 if (match(V: &I, P: m_c_And(L: m_OneUse(SubPattern: m_SExtOrSelf(
2914 Op: m_Not(V: m_AShr(L: m_Value(V&: X), R: m_APIntAllowPoison(Res&: C))))),
2915 R: m_Value(V&: Y))) &&
2916 *C == X->getType()->getScalarSizeInBits() - 1) {
2917 Value *IsNeg = Builder.CreateIsNeg(Arg: X, Name: "isneg");
2918 return createSelectInstWithUnknownProfile(C: IsNeg,
2919 S1: ConstantInt::getNullValue(Ty), S2: Y);
2920 }
2921
2922 // (~x) & y --> ~(x | (~y)) iff that gets rid of inversions
2923 if (sinkNotIntoOtherHandOfLogicalOp(I))
2924 return &I;
2925
2926 // An and recurrence w/loop invariant step is equivelent to (and start, step)
2927 PHINode *PN = nullptr;
2928 Value *Start = nullptr, *Step = nullptr;
2929 if (matchSimpleRecurrence(I: &I, P&: PN, Start, Step) && DT.dominates(Def: Step, User: PN))
2930 return replaceInstUsesWith(I, V: Builder.CreateAnd(LHS: Start, RHS: Step));
2931
2932 if (Instruction *R = reassociateForUses(BO&: I, Builder))
2933 return R;
2934
2935 if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
2936 return Canonicalized;
2937
2938 if (Instruction *Folded = foldLogicOfIsFPClass(BO&: I, Op0, Op1))
2939 return Folded;
2940
2941 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2942 return Res;
2943
2944 if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
2945 return Res;
2946
2947 if (Value *V =
2948 simplifyAndOrWithOpReplaced(V: Op0, Op: Op1, RepOp: Constant::getAllOnesValue(Ty),
2949 /*SimplifyOnly*/ false, IC&: *this))
2950 return BinaryOperator::CreateAnd(V1: V, V2: Op1);
2951 if (Value *V =
2952 simplifyAndOrWithOpReplaced(V: Op1, Op: Op0, RepOp: Constant::getAllOnesValue(Ty),
2953 /*SimplifyOnly*/ false, IC&: *this))
2954 return BinaryOperator::CreateAnd(V1: Op0, V2: V);
2955
2956 if (Instruction *Res = foldRoundUpToPow2Alignment(I, Builder))
2957 return Res;
2958
2959 return nullptr;
2960}
2961
2962Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2963 bool MatchBSwaps,
2964 bool MatchBitReversals) {
2965 SmallVector<Instruction *, 4> Insts;
2966 if (!recognizeBSwapOrBitReverseIdiom(I: &I, MatchBSwaps, MatchBitReversals,
2967 InsertedInsts&: Insts))
2968 return nullptr;
2969 Instruction *LastInst = Insts.pop_back_val();
2970 LastInst->removeFromParent();
2971
2972 for (auto *Inst : Insts) {
2973 Inst->setDebugLoc(I.getDebugLoc());
2974 Worklist.push(I: Inst);
2975 }
2976 return LastInst;
2977}
2978
2979std::optional<std::pair<Intrinsic::ID, SmallVector<Value *, 3>>>
2980InstCombinerImpl::convertOrOfShiftsToFunnelShift(Instruction &Or) {
2981 // TODO: Can we reduce the code duplication between this and the related
2982 // rotate matching code under visitSelect and visitTrunc?
2983 assert(Or.getOpcode() == BinaryOperator::Or && "Expecting or instruction");
2984
2985 unsigned Width = Or.getType()->getScalarSizeInBits();
2986
2987 Instruction *Or0, *Or1;
2988 if (!match(V: Or.getOperand(i: 0), P: m_Instruction(I&: Or0)) ||
2989 !match(V: Or.getOperand(i: 1), P: m_Instruction(I&: Or1)))
2990 return std::nullopt;
2991
2992 bool IsFshl = true; // Sub on LSHR.
2993 SmallVector<Value *, 3> FShiftArgs;
2994
2995 // First, find an or'd pair of opposite shifts:
2996 // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2997 if (isa<BinaryOperator>(Val: Or0) && isa<BinaryOperator>(Val: Or1)) {
2998 Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2999 if (!match(V: Or0,
3000 P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: ShVal0), R: m_Value(V&: ShAmt0)))) ||
3001 !match(V: Or1,
3002 P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: ShVal1), R: m_Value(V&: ShAmt1)))) ||
3003 Or0->getOpcode() == Or1->getOpcode())
3004 return std::nullopt;
3005
3006 // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
3007 if (Or0->getOpcode() == BinaryOperator::LShr) {
3008 std::swap(a&: Or0, b&: Or1);
3009 std::swap(a&: ShVal0, b&: ShVal1);
3010 std::swap(a&: ShAmt0, b&: ShAmt1);
3011 }
3012 assert(Or0->getOpcode() == BinaryOperator::Shl &&
3013 Or1->getOpcode() == BinaryOperator::LShr &&
3014 "Illegal or(shift,shift) pair");
3015
3016 // Match the shift amount operands for a funnel shift pattern. This always
3017 // matches a subtraction on the R operand.
3018 auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
3019 // Check for constant shift amounts that sum to the bitwidth.
3020 const APInt *LI, *RI;
3021 if (match(V: L, P: m_APIntAllowPoison(Res&: LI)) && match(V: R, P: m_APIntAllowPoison(Res&: RI)))
3022 if (LI->ult(RHS: Width) && RI->ult(RHS: Width) && (*LI + *RI) == Width)
3023 return ConstantInt::get(Ty: L->getType(), V: *LI);
3024
3025 Constant *LC, *RC;
3026 if (match(V: L, P: m_Constant(C&: LC)) && match(V: R, P: m_Constant(C&: RC)) &&
3027 match(V: L,
3028 P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_ULT, Threshold: APInt(Width, Width))) &&
3029 match(V: R,
3030 P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_ULT, Threshold: APInt(Width, Width))) &&
3031 match(V: ConstantExpr::getAdd(C1: LC, C2: RC), P: m_SpecificIntAllowPoison(V: Width)))
3032 return ConstantExpr::mergeUndefsWith(C: LC, Other: RC);
3033
3034 // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
3035 // We limit this to X < Width in case the backend re-expands the
3036 // intrinsic, and has to reintroduce a shift modulo operation (InstCombine
3037 // might remove it after this fold). This still doesn't guarantee that the
3038 // final codegen will match this original pattern.
3039 if (match(V: R, P: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: Width), R: m_Specific(V: L))))) {
3040 KnownBits KnownL = computeKnownBits(V: L, CxtI: &Or);
3041 return KnownL.getMaxValue().ult(RHS: Width) ? L : nullptr;
3042 }
3043
3044 // For non-constant cases, the following patterns currently only work for
3045 // rotation patterns.
3046 // TODO: Add general funnel-shift compatible patterns.
3047 if (ShVal0 != ShVal1)
3048 return nullptr;
3049
3050 // For non-constant cases we don't support non-pow2 shift masks.
3051 // TODO: Is it worth matching urem as well?
3052 if (!isPowerOf2_32(Value: Width))
3053 return nullptr;
3054
3055 // The shift amount may be masked with negation:
3056 // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
3057 Value *X;
3058 unsigned Mask = Width - 1;
3059 if (match(V: L, P: m_And(L: m_Value(V&: X), R: m_SpecificInt(V: Mask))) &&
3060 match(V: R, P: m_And(L: m_Neg(V: m_Specific(V: X)), R: m_SpecificInt(V: Mask))))
3061 return X;
3062
3063 // (shl ShVal,(X+1) & (Width-1)) | (lshr ShVal,((X & (Width-1)) ^
3064 // (Width-1)))
3065 {
3066 Value *XPlusOne = nullptr;
3067 if (match(V: L, P: m_And(L: m_Value(V&: XPlusOne, P: m_Add(L: m_Value(V&: X), R: m_One())),
3068 R: m_SpecificInt(V: Mask))) &&
3069 match(V: R, P: m_Xor(L: m_And(L: m_Specific(V: X), R: m_SpecificInt(V: Mask)),
3070 R: m_SpecificInt(V: Mask))))
3071 return XPlusOne;
3072 }
3073
3074 // (shl ShVal, X) | (lshr ShVal, ((-X) & (Width - 1)))
3075 if (match(V: R, P: m_And(L: m_Neg(V: m_Specific(V: L)), R: m_SpecificInt(V: Mask))))
3076 return L;
3077
3078 // Similar to above, but the shift amount may be extended after masking,
3079 // so return the extended value as the parameter for the intrinsic.
3080 if (match(V: L, P: m_ZExt(Op: m_And(L: m_Value(V&: X), R: m_SpecificInt(V: Mask)))) &&
3081 match(V: R,
3082 P: m_And(L: m_Neg(V: m_ZExt(Op: m_And(L: m_Specific(V: X), R: m_SpecificInt(V: Mask)))),
3083 R: m_SpecificInt(V: Mask))))
3084 return L;
3085
3086 if (match(V: L, P: m_ZExt(Op: m_And(L: m_Value(V&: X), R: m_SpecificInt(V: Mask)))) &&
3087 match(V: R, P: m_ZExt(Op: m_And(L: m_Neg(V: m_Specific(V: X)), R: m_SpecificInt(V: Mask)))))
3088 return L;
3089
3090 return nullptr;
3091 };
3092
3093 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
3094 if (!ShAmt) {
3095 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
3096 IsFshl = false; // Sub on SHL.
3097 }
3098 if (!ShAmt)
3099 return std::nullopt;
3100
3101 FShiftArgs = {ShVal0, ShVal1, ShAmt};
3102 } else if (isa<ZExtInst>(Val: Or0) || isa<ZExtInst>(Val: Or1)) {
3103 // If there are two 'or' instructions concat variables in opposite order:
3104 //
3105 // Slot1 and Slot2 are all zero bits.
3106 // | Slot1 | Low | Slot2 | High |
3107 // LowHigh = or (shl (zext Low), ZextLowShlAmt), (zext High)
3108 // | Slot2 | High | Slot1 | Low |
3109 // HighLow = or (shl (zext High), ZextHighShlAmt), (zext Low)
3110 //
3111 // the latter 'or' can be safely convert to
3112 // -> HighLow = fshl LowHigh, LowHigh, ZextHighShlAmt
3113 // if ZextLowShlAmt + ZextHighShlAmt == Width.
3114 if (!isa<ZExtInst>(Val: Or1))
3115 std::swap(a&: Or0, b&: Or1);
3116
3117 Value *High, *ZextHigh, *Low;
3118 const APInt *ZextHighShlAmt;
3119 if (!match(V: Or0,
3120 P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: ZextHigh), R: m_APInt(Res&: ZextHighShlAmt)))))
3121 return std::nullopt;
3122
3123 if (!match(V: Or1, P: m_ZExt(Op: m_Value(V&: Low))) ||
3124 !match(V: ZextHigh, P: m_ZExt(Op: m_Value(V&: High))))
3125 return std::nullopt;
3126
3127 unsigned HighSize = High->getType()->getScalarSizeInBits();
3128 unsigned LowSize = Low->getType()->getScalarSizeInBits();
3129 // Make sure High does not overlap with Low and most significant bits of
3130 // High aren't shifted out.
3131 if (ZextHighShlAmt->ult(RHS: LowSize) || ZextHighShlAmt->ugt(RHS: Width - HighSize))
3132 return std::nullopt;
3133
3134 for (User *U : ZextHigh->users()) {
3135 Value *X, *Y;
3136 if (!match(V: U, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))))
3137 continue;
3138
3139 if (!isa<ZExtInst>(Val: Y))
3140 std::swap(a&: X, b&: Y);
3141
3142 const APInt *ZextLowShlAmt;
3143 if (!match(V: X, P: m_Shl(L: m_Specific(V: Or1), R: m_APInt(Res&: ZextLowShlAmt))) ||
3144 !match(V: Y, P: m_Specific(V: ZextHigh)) || !DT.dominates(Def: U, User: &Or))
3145 continue;
3146
3147 // HighLow is good concat. If sum of two shifts amount equals to Width,
3148 // LowHigh must also be a good concat.
3149 if (*ZextLowShlAmt + *ZextHighShlAmt != Width)
3150 continue;
3151
3152 // Low must not overlap with High and most significant bits of Low must
3153 // not be shifted out.
3154 assert(ZextLowShlAmt->uge(HighSize) &&
3155 ZextLowShlAmt->ule(Width - LowSize) && "Invalid concat");
3156
3157 // We cannot reuse the result if it may produce poison.
3158 // Drop poison generating flags in the expression tree.
3159 // Or
3160 cast<Instruction>(Val: U)->dropPoisonGeneratingFlags();
3161 // Shl
3162 cast<Instruction>(Val: X)->dropPoisonGeneratingFlags();
3163
3164 FShiftArgs = {U, U, ConstantInt::get(Ty: Or0->getType(), V: *ZextHighShlAmt)};
3165 break;
3166 }
3167 }
3168
3169 if (FShiftArgs.empty())
3170 return std::nullopt;
3171
3172 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
3173 return std::make_pair(x&: IID, y&: FShiftArgs);
3174}
3175
3176/// Match UB-safe variants of the funnel shift intrinsic.
3177static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
3178 if (auto Opt = IC.convertOrOfShiftsToFunnelShift(Or)) {
3179 auto [IID, FShiftArgs] = *Opt;
3180 Function *F =
3181 Intrinsic::getOrInsertDeclaration(M: Or.getModule(), id: IID, OverloadTys: Or.getType());
3182 return CallInst::Create(Func: F, Args: FShiftArgs);
3183 }
3184
3185 return nullptr;
3186}
3187
3188/// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
3189static Value *matchOrConcat(Instruction &Or, InstCombiner::BuilderTy &Builder) {
3190 assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
3191 Value *Op0 = Or.getOperand(i: 0), *Op1 = Or.getOperand(i: 1);
3192 Type *Ty = Or.getType();
3193
3194 unsigned Width = Ty->getScalarSizeInBits();
3195 if ((Width & 1) != 0)
3196 return nullptr;
3197 unsigned HalfWidth = Width / 2;
3198
3199 // Canonicalize zext (lower half) to LHS.
3200 if (!isa<ZExtInst>(Val: Op0))
3201 std::swap(a&: Op0, b&: Op1);
3202
3203 // Find lower/upper half.
3204 Value *LowerSrc, *ShlVal, *UpperSrc;
3205 const APInt *C;
3206 if (!match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: LowerSrc)))) ||
3207 !match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: ShlVal), R: m_APInt(Res&: C)))) ||
3208 !match(V: ShlVal, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: UpperSrc)))))
3209 return nullptr;
3210 if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
3211 LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
3212 return nullptr;
3213
3214 auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
3215 Value *NewLower = Builder.CreateZExt(V: Lo, DestTy: Ty);
3216 Value *NewUpper = Builder.CreateZExt(V: Hi, DestTy: Ty);
3217 NewUpper = Builder.CreateShl(LHS: NewUpper, RHS: HalfWidth);
3218 Value *BinOp = Builder.CreateDisjointOr(LHS: NewLower, RHS: NewUpper);
3219 return Builder.CreateIntrinsic(ID: id, OverloadTypes: Ty, Args: BinOp);
3220 };
3221
3222 // BSWAP: Push the concat down, swapping the lower/upper sources.
3223 // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
3224 Value *LowerBSwap, *UpperBSwap;
3225 if (match(V: LowerSrc, P: m_BSwap(Op0: m_Value(V&: LowerBSwap))) &&
3226 match(V: UpperSrc, P: m_BSwap(Op0: m_Value(V&: UpperBSwap))))
3227 return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
3228
3229 // BITREVERSE: Push the concat down, swapping the lower/upper sources.
3230 // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
3231 Value *LowerBRev, *UpperBRev;
3232 if (match(V: LowerSrc, P: m_BitReverse(Op0: m_Value(V&: LowerBRev))) &&
3233 match(V: UpperSrc, P: m_BitReverse(Op0: m_Value(V&: UpperBRev))))
3234 return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
3235
3236 // iX ext split: extending or(zext(x),shl(zext(y),bw/2) pattern
3237 // to consume sext/ashr:
3238 // or(zext(sext(x)),shl(zext(sext(ashr(x,xbw-1))),bw/2)
3239 // or(zext(x),shl(zext(ashr(x,xbw-1)),bw/2)
3240 Value *X;
3241 if (match(V: LowerSrc, P: m_SExtOrSelf(Op: m_Value(V&: X))) &&
3242 match(V: UpperSrc,
3243 P: m_SExtOrSelf(Op: m_AShr(
3244 L: m_Specific(V: X),
3245 R: m_SpecificInt(V: X->getType()->getScalarSizeInBits() - 1)))))
3246 return Builder.CreateSExt(V: X, DestTy: Ty);
3247
3248 return nullptr;
3249}
3250
3251/// If all elements of two constant vectors are 0/-1 and inverses, return true.
3252static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
3253 unsigned NumElts = cast<FixedVectorType>(Val: C1->getType())->getNumElements();
3254 for (unsigned i = 0; i != NumElts; ++i) {
3255 Constant *EltC1 = C1->getAggregateElement(Elt: i);
3256 Constant *EltC2 = C2->getAggregateElement(Elt: i);
3257 if (!EltC1 || !EltC2)
3258 return false;
3259
3260 // One element must be all ones, and the other must be all zeros.
3261 if (!((match(V: EltC1, P: m_Zero()) && match(V: EltC2, P: m_AllOnes())) ||
3262 (match(V: EltC2, P: m_Zero()) && match(V: EltC1, P: m_AllOnes()))))
3263 return false;
3264 }
3265 return true;
3266}
3267
3268/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
3269/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
3270/// B, it can be used as the condition operand of a select instruction.
3271/// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
3272Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
3273 bool ABIsTheSame) {
3274 // We may have peeked through bitcasts in the caller.
3275 // Exit immediately if we don't have (vector) integer types.
3276 Type *Ty = A->getType();
3277 if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
3278 return nullptr;
3279
3280 // If A is the 'not' operand of B and has enough signbits, we have our answer.
3281 if (ABIsTheSame ? (A == B) : match(V: B, P: m_Not(V: m_Specific(V: A)))) {
3282 // If these are scalars or vectors of i1, A can be used directly.
3283 if (Ty->isIntOrIntVectorTy(BitWidth: 1))
3284 return A;
3285
3286 // If we look through a vector bitcast, the caller will bitcast the operands
3287 // to match the condition's number of bits (N x i1).
3288 // To make this poison-safe, disallow bitcast from wide element to narrow
3289 // element. That could allow poison in lanes where it was not present in the
3290 // original code.
3291 A = peekThroughBitcast(V: A);
3292 if (A->getType()->isIntOrIntVectorTy()) {
3293 unsigned NumSignBits = ComputeNumSignBits(Op: A);
3294 if (NumSignBits == A->getType()->getScalarSizeInBits() &&
3295 NumSignBits <= Ty->getScalarSizeInBits())
3296 return Builder.CreateTrunc(V: A, DestTy: CmpInst::makeCmpResultType(opnd_type: A->getType()));
3297 }
3298 return nullptr;
3299 }
3300
3301 // TODO: add support for sext and constant case
3302 if (ABIsTheSame)
3303 return nullptr;
3304
3305 // If both operands are constants, see if the constants are inverse bitmasks.
3306 Constant *AConst, *BConst;
3307 if (match(V: A, P: m_Constant(C&: AConst)) && match(V: B, P: m_Constant(C&: BConst)))
3308 if (AConst == ConstantExpr::getNot(C: BConst) &&
3309 ComputeNumSignBits(Op: A) == Ty->getScalarSizeInBits())
3310 return Builder.CreateZExtOrTrunc(V: A, DestTy: CmpInst::makeCmpResultType(opnd_type: Ty));
3311
3312 // Look for more complex patterns. The 'not' op may be hidden behind various
3313 // casts. Look through sexts and bitcasts to find the booleans.
3314 Value *Cond;
3315 Value *NotB;
3316 if (match(V: A, P: m_SExt(Op: m_Value(V&: Cond))) &&
3317 Cond->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
3318 // A = sext i1 Cond; B = sext (not (i1 Cond))
3319 if (match(V: B, P: m_SExt(Op: m_Not(V: m_Specific(V: Cond)))))
3320 return Cond;
3321
3322 // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
3323 // TODO: The one-use checks are unnecessary or misplaced. If the caller
3324 // checked for uses on logic ops/casts, that should be enough to
3325 // make this transform worthwhile.
3326 if (match(V: B, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotB))))) {
3327 NotB = peekThroughBitcast(V: NotB, OneUseOnly: true);
3328 if (match(V: NotB, P: m_SExt(Op: m_Specific(V: Cond))))
3329 return Cond;
3330 }
3331 }
3332
3333 // All scalar (and most vector) possibilities should be handled now.
3334 // Try more matches that only apply to non-splat constant vectors.
3335 if (!Ty->isVectorTy())
3336 return nullptr;
3337
3338 // If both operands are xor'd with constants using the same sexted boolean
3339 // operand, see if the constants are inverse bitmasks.
3340 // TODO: Use ConstantExpr::getNot()?
3341 if (match(V: A, P: (m_Xor(L: m_SExt(Op: m_Value(V&: Cond)), R: m_Constant(C&: AConst)))) &&
3342 match(V: B, P: (m_Xor(L: m_SExt(Op: m_Specific(V: Cond)), R: m_Constant(C&: BConst)))) &&
3343 Cond->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
3344 areInverseVectorBitmasks(C1: AConst, C2: BConst)) {
3345 AConst = ConstantExpr::getTrunc(C: AConst, Ty: CmpInst::makeCmpResultType(opnd_type: Ty));
3346 return Builder.CreateXor(LHS: Cond, RHS: AConst);
3347 }
3348 return nullptr;
3349}
3350
3351/// We have an expression of the form (A & B) | (C & D). Try to simplify this
3352/// to "A' ? B : D", where A' is a boolean or vector of booleans.
3353/// When InvertFalseVal is set to true, we try to match the pattern
3354/// where we have peeked through a 'not' op and A and C are the same:
3355/// (A & B) | ~(A | D) --> (A & B) | (~A & ~D) --> A' ? B : ~D
3356Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *B, Value *C,
3357 Value *D, bool InvertFalseVal) {
3358 // The potential condition of the select may be bitcasted. In that case, look
3359 // through its bitcast and the corresponding bitcast of the 'not' condition.
3360 Type *OrigType = A->getType();
3361 A = peekThroughBitcast(V: A, OneUseOnly: true);
3362 C = peekThroughBitcast(V: C, OneUseOnly: true);
3363 if (Value *Cond = getSelectCondition(A, B: C, ABIsTheSame: InvertFalseVal)) {
3364 // ((bc Cond) & B) | ((bc ~Cond) & D) --> bc (select Cond, (bc B), (bc D))
3365 // If this is a vector, we may need to cast to match the condition's length.
3366 // The bitcasts will either all exist or all not exist. The builder will
3367 // not create unnecessary casts if the types already match.
3368 Type *SelTy = A->getType();
3369 if (auto *VecTy = dyn_cast<VectorType>(Val: Cond->getType())) {
3370 // For a fixed or scalable vector get N from <{vscale x} N x iM>
3371 unsigned Elts = VecTy->getElementCount().getKnownMinValue();
3372 // For a fixed or scalable vector, get the size in bits of N x iM; for a
3373 // scalar this is just M.
3374 unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
3375 Type *EltTy = Builder.getIntNTy(N: SelEltSize / Elts);
3376 SelTy = VectorType::get(ElementType: EltTy, EC: VecTy->getElementCount());
3377 }
3378 Value *BitcastB = Builder.CreateBitCast(V: B, DestTy: SelTy);
3379 if (InvertFalseVal)
3380 D = Builder.CreateNot(V: D);
3381 Value *BitcastD = Builder.CreateBitCast(V: D, DestTy: SelTy);
3382 Value *Select = Builder.CreateSelect(C: Cond, True: BitcastB, False: BitcastD);
3383 return Builder.CreateBitCast(V: Select, DestTy: OrigType);
3384 }
3385
3386 return nullptr;
3387}
3388
3389// (icmp eq X, C) | (icmp ult Other, (X - C)) -> (icmp ule Other, (X - (C + 1)))
3390// (icmp ne X, C) & (icmp uge Other, (X - C)) -> (icmp ugt Other, (X - (C + 1)))
3391static Value *foldAndOrOfICmpEqConstantAndICmp(ICmpInst *LHS, ICmpInst *RHS,
3392 bool IsAnd, bool IsLogical,
3393 IRBuilderBase &Builder) {
3394 Value *LHS0 = LHS->getOperand(i_nocapture: 0);
3395 Value *RHS0 = RHS->getOperand(i_nocapture: 0);
3396 Value *RHS1 = RHS->getOperand(i_nocapture: 1);
3397
3398 ICmpInst::Predicate LPred =
3399 IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
3400 ICmpInst::Predicate RPred =
3401 IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
3402
3403 const APInt *CInt;
3404 if (LPred != ICmpInst::ICMP_EQ ||
3405 !match(V: LHS->getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: CInt)) ||
3406 !LHS0->getType()->isIntOrIntVectorTy() ||
3407 !(LHS->hasOneUse() || RHS->hasOneUse()))
3408 return nullptr;
3409
3410 auto MatchRHSOp = [LHS0, CInt](const Value *RHSOp) {
3411 return match(V: RHSOp,
3412 P: m_Add(L: m_Specific(V: LHS0), R: m_SpecificIntAllowPoison(V: -*CInt))) ||
3413 (CInt->isZero() && RHSOp == LHS0);
3414 };
3415
3416 Value *Other;
3417 if (RPred == ICmpInst::ICMP_ULT && MatchRHSOp(RHS1))
3418 Other = RHS0;
3419 else if (RPred == ICmpInst::ICMP_UGT && MatchRHSOp(RHS0))
3420 Other = RHS1;
3421 else
3422 return nullptr;
3423
3424 if (IsLogical)
3425 Other = Builder.CreateFreeze(V: Other);
3426
3427 return Builder.CreateICmp(
3428 P: IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
3429 LHS: Builder.CreateSub(LHS: LHS0, RHS: ConstantInt::get(Ty: LHS0->getType(), V: *CInt + 1)),
3430 RHS: Other);
3431}
3432
3433/// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
3434/// If IsLogical is true, then the and/or is in select form and the transform
3435/// must be poison-safe.
3436Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3437 Instruction &I, bool IsAnd,
3438 bool IsLogical) {
3439 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
3440
3441 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3442 Value *LHS0 = LHS->getOperand(i_nocapture: 0), *RHS0 = RHS->getOperand(i_nocapture: 0);
3443 Value *LHS1 = LHS->getOperand(i_nocapture: 1), *RHS1 = RHS->getOperand(i_nocapture: 1);
3444
3445 const APInt *LHSC = nullptr, *RHSC = nullptr;
3446 match(V: LHS1, P: m_APInt(Res&: LHSC));
3447 match(V: RHS1, P: m_APInt(Res&: RHSC));
3448
3449 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3450 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3451 if (predicatesFoldable(P1: PredL, P2: PredR)) {
3452 if (LHS0 == RHS1 && LHS1 == RHS0) {
3453 PredL = ICmpInst::getSwappedPredicate(pred: PredL);
3454 std::swap(a&: LHS0, b&: LHS1);
3455 }
3456 if (LHS0 == RHS0 && LHS1 == RHS1) {
3457 unsigned Code = IsAnd ? getICmpCode(Pred: PredL) & getICmpCode(Pred: PredR)
3458 : getICmpCode(Pred: PredL) | getICmpCode(Pred: PredR);
3459 bool IsSigned = LHS->isSigned() || RHS->isSigned();
3460 return getNewICmpValue(Code, Sign: IsSigned, LHS: LHS0, RHS: LHS1, Builder);
3461 }
3462 }
3463
3464 if (Value *V =
3465 foldAndOrOfICmpEqConstantAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
3466 return V;
3467 // We can treat logical like bitwise here, because both operands are used on
3468 // the LHS, and as such poison from both will propagate.
3469 if (Value *V = foldAndOrOfICmpEqConstantAndICmp(LHS: RHS, RHS: LHS, IsAnd,
3470 /*IsLogical*/ false, Builder))
3471 return V;
3472
3473 if (Value *V = foldAndOrOfICmpsWithConstEq(Cmp0: LHS, Cmp1: RHS, IsAnd, IsLogical,
3474 Builder, Q, I))
3475 return V;
3476 // We can convert this case to bitwise and, because both operands are used
3477 // on the LHS, and as such poison from both will propagate.
3478 if (Value *V = foldAndOrOfICmpsWithConstEq(
3479 Cmp0: RHS, Cmp1: LHS, IsAnd, /*IsLogical=*/false, Builder, Q, I)) {
3480 // If RHS is still used, we should drop samesign flag.
3481 if (IsLogical && RHS->hasSameSign() && !RHS->use_empty()) {
3482 RHS->setSameSign(false);
3483 addToWorklist(I: RHS);
3484 }
3485 return V;
3486 }
3487
3488 if (Value *V = foldIsPowerOf2OrZero(Cmp0: LHS, Cmp1: RHS, IsAnd, Builder, IC&: *this))
3489 return V;
3490 if (Value *V = foldIsPowerOf2OrZero(Cmp0: RHS, Cmp1: LHS, IsAnd, Builder, IC&: *this))
3491 return V;
3492
3493 // TODO: One of these directions is fine with logical and/or, the other could
3494 // be supported by inserting freeze.
3495 if (!IsLogical) {
3496 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
3497 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
3498 if (Value *V = simplifyRangeCheck(Cmp0: LHS, Cmp1: RHS, /*Inverted=*/!IsAnd))
3499 return V;
3500
3501 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
3502 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
3503 if (Value *V = simplifyRangeCheck(Cmp0: RHS, Cmp1: LHS, /*Inverted=*/!IsAnd))
3504 return V;
3505 }
3506
3507 // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
3508 if (IsAnd && !IsLogical)
3509 if (Value *V = foldSignedTruncationCheck(ICmp0: LHS, ICmp1: RHS, CxtI&: I, Builder))
3510 return V;
3511
3512 if (Value *V = foldIsPowerOf2(Cmp0: LHS, Cmp1: RHS, JoinedByAnd: IsAnd, Builder, IC&: *this))
3513 return V;
3514
3515 if (Value *V = foldPowerOf2AndShiftedMask(Cmp0: LHS, Cmp1: RHS, JoinedByAnd: IsAnd, Builder))
3516 return V;
3517
3518 // TODO: Verify whether this is safe for logical and/or.
3519 if (!IsLogical) {
3520 if (Value *X = foldUnsignedUnderflowCheck(ZeroICmp: LHS, UnsignedICmp: RHS, IsAnd, Q, Builder))
3521 return X;
3522 if (Value *X = foldUnsignedUnderflowCheck(ZeroICmp: RHS, UnsignedICmp: LHS, IsAnd, Q, Builder))
3523 return X;
3524 }
3525
3526 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
3527 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
3528 // TODO: Remove this and below when foldLogOpOfMaskedICmps can handle undefs.
3529 if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3530 PredL == PredR && match(V: LHS1, P: m_ZeroInt()) && match(V: RHS1, P: m_ZeroInt()) &&
3531 LHS0->getType() == RHS0->getType() &&
3532 (!IsLogical || isGuaranteedNotToBePoison(V: RHS0))) {
3533 Value *NewOr = Builder.CreateOr(LHS: LHS0, RHS: RHS0);
3534 return Builder.CreateICmp(P: PredL, LHS: NewOr,
3535 RHS: Constant::getNullValue(Ty: NewOr->getType()));
3536 }
3537
3538 // (icmp ne A, -1) | (icmp ne B, -1) --> (icmp ne (A&B), -1)
3539 // (icmp eq A, -1) & (icmp eq B, -1) --> (icmp eq (A&B), -1)
3540 if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3541 PredL == PredR && match(V: LHS1, P: m_AllOnes()) && match(V: RHS1, P: m_AllOnes()) &&
3542 LHS0->getType() == RHS0->getType() &&
3543 (!IsLogical || isGuaranteedNotToBePoison(V: RHS0))) {
3544 Value *NewAnd = Builder.CreateAnd(LHS: LHS0, RHS: RHS0);
3545 return Builder.CreateICmp(P: PredL, LHS: NewAnd,
3546 RHS: Constant::getAllOnesValue(Ty: LHS0->getType()));
3547 }
3548
3549 if (!IsLogical)
3550 if (Value *V =
3551 foldAndOrOfICmpsWithPow2AndWithZero(Builder, LHS, RHS, IsAnd, Q))
3552 return V;
3553
3554 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
3555 if (!LHSC || !RHSC)
3556 return nullptr;
3557
3558 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
3559 // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
3560 // where CMAX is the all ones value for the truncated type,
3561 // iff the lower bits of C2 and CA are zero.
3562 if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
3563 PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
3564 Value *V;
3565 const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
3566
3567 // (trunc x) == C1 & (and x, CA) == C2
3568 // (and x, CA) == C2 & (trunc x) == C1
3569 if (match(V: RHS0, P: m_Trunc(Op: m_Value(V))) &&
3570 match(V: LHS0, P: m_And(L: m_Specific(V), R: m_APInt(Res&: AndC)))) {
3571 SmallC = RHSC;
3572 BigC = LHSC;
3573 } else if (match(V: LHS0, P: m_Trunc(Op: m_Value(V))) &&
3574 match(V: RHS0, P: m_And(L: m_Specific(V), R: m_APInt(Res&: AndC)))) {
3575 SmallC = LHSC;
3576 BigC = RHSC;
3577 }
3578
3579 if (SmallC && BigC) {
3580 unsigned BigBitSize = BigC->getBitWidth();
3581 unsigned SmallBitSize = SmallC->getBitWidth();
3582
3583 // Check that the low bits are zero.
3584 APInt Low = APInt::getLowBitsSet(numBits: BigBitSize, loBitsSet: SmallBitSize);
3585 if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
3586 Value *NewAnd = Builder.CreateAnd(LHS: V, RHS: Low | *AndC);
3587 APInt N = SmallC->zext(width: BigBitSize) | *BigC;
3588 Value *NewVal = ConstantInt::get(Ty: NewAnd->getType(), V: N);
3589 return Builder.CreateICmp(P: PredL, LHS: NewAnd, RHS: NewVal);
3590 }
3591 }
3592 }
3593
3594 // Match naive pattern (and its inverted form) for checking if two values
3595 // share same sign. An example of the pattern:
3596 // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
3597 // Inverted form (example):
3598 // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
3599 bool TrueIfSignedL, TrueIfSignedR;
3600 if (isSignBitCheck(Pred: PredL, RHS: *LHSC, TrueIfSigned&: TrueIfSignedL) &&
3601 isSignBitCheck(Pred: PredR, RHS: *RHSC, TrueIfSigned&: TrueIfSignedR) &&
3602 (RHS->hasOneUse() || LHS->hasOneUse())) {
3603 Value *X, *Y;
3604 if (IsAnd) {
3605 if ((TrueIfSignedL && !TrueIfSignedR &&
3606 match(V: LHS0, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3607 match(V: RHS0, P: m_c_And(L: m_Specific(V: X), R: m_Specific(V: Y)))) ||
3608 (!TrueIfSignedL && TrueIfSignedR &&
3609 match(V: LHS0, P: m_And(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3610 match(V: RHS0, P: m_c_Or(L: m_Specific(V: X), R: m_Specific(V: Y))))) {
3611 Value *NewXor = Builder.CreateXor(LHS: X, RHS: Y);
3612 return Builder.CreateIsNeg(Arg: NewXor);
3613 }
3614 } else {
3615 if ((TrueIfSignedL && !TrueIfSignedR &&
3616 match(V: LHS0, P: m_And(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3617 match(V: RHS0, P: m_c_Or(L: m_Specific(V: X), R: m_Specific(V: Y)))) ||
3618 (!TrueIfSignedL && TrueIfSignedR &&
3619 match(V: LHS0, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3620 match(V: RHS0, P: m_c_And(L: m_Specific(V: X), R: m_Specific(V: Y))))) {
3621 Value *NewXor = Builder.CreateXor(LHS: X, RHS: Y);
3622 return Builder.CreateIsNotNeg(Arg: NewXor);
3623 }
3624 }
3625 }
3626
3627 // (X & ExpMask) != 0 && (X & ExpMask) != ExpMask -> isnormal(X)
3628 // (X & ExpMask) == 0 || (X & ExpMask) == ExpMask -> !isnormal(X)
3629 Value *X;
3630 const APInt *MaskC;
3631 if (LHS0 == RHS0 && PredL == PredR &&
3632 PredL == (IsAnd ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ) &&
3633 !I.getFunction()->hasFnAttribute(Kind: Attribute::NoImplicitFloat) &&
3634 LHS->hasOneUse() && RHS->hasOneUse() &&
3635 match(V: LHS0, P: m_And(L: m_ElementWiseBitCast(Op: m_Value(V&: X)), R: m_APInt(Res&: MaskC))) &&
3636 X->getType()->getScalarType()->isIEEELikeFPTy() &&
3637 APFloat(X->getType()->getScalarType()->getFltSemantics(), *MaskC)
3638 .isPosInfinity() &&
3639 ((LHSC->isZero() && *RHSC == *MaskC) ||
3640 (RHSC->isZero() && *LHSC == *MaskC)))
3641 return Builder.createIsFPClass(FPNum: X, Test: IsAnd ? FPClassTest::fcNormal
3642 : ~FPClassTest::fcNormal);
3643
3644 return foldAndOrOfICmpsUsingRanges(ICmp1: LHS, ICmp2: RHS, IsAnd);
3645}
3646
3647/// If IsLogical is true, then the and/or is in select form and the transform
3648/// must be poison-safe.
3649Value *InstCombinerImpl::foldBooleanAndOr(Value *LHS, Value *RHS,
3650 Instruction &I, bool IsAnd,
3651 bool IsLogical) {
3652 if (!LHS->getType()->isIntOrIntVectorTy(BitWidth: 1))
3653 return nullptr;
3654
3655 // handle (roughly):
3656 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
3657 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
3658 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder,
3659 Q: SQ.getWithInstruction(I: &I)))
3660 return V;
3661
3662 if (auto *LHSCmp = dyn_cast<ICmpInst>(Val: LHS))
3663 if (auto *RHSCmp = dyn_cast<ICmpInst>(Val: RHS))
3664 if (Value *Res = foldAndOrOfICmps(LHS: LHSCmp, RHS: RHSCmp, I, IsAnd, IsLogical))
3665 return Res;
3666
3667 if (auto *LHSCmp = dyn_cast<FCmpInst>(Val: LHS))
3668 if (auto *RHSCmp = dyn_cast<FCmpInst>(Val: RHS))
3669 if (Value *Res = foldLogicOfFCmps(LHS: LHSCmp, RHS: RHSCmp, IsAnd, IsLogicalSelect: IsLogical))
3670 return Res;
3671
3672 if (Value *Res = foldEqOfParts(Cmp0: LHS, Cmp1: RHS, IsAnd))
3673 return Res;
3674
3675 return nullptr;
3676}
3677
3678static Value *foldOrOfInversions(BinaryOperator &I,
3679 InstCombiner::BuilderTy &Builder) {
3680 assert(I.getOpcode() == Instruction::Or &&
3681 "Simplification only supports or at the moment.");
3682
3683 Value *Cmp1, *Cmp2, *Cmp3, *Cmp4;
3684 if (!match(V: I.getOperand(i_nocapture: 0), P: m_And(L: m_Value(V&: Cmp1), R: m_Value(V&: Cmp2))) ||
3685 !match(V: I.getOperand(i_nocapture: 1), P: m_And(L: m_Value(V&: Cmp3), R: m_Value(V&: Cmp4))))
3686 return nullptr;
3687
3688 // Check if any two pairs of the and operations are inversions of each other.
3689 if (isKnownInversion(X: Cmp1, Y: Cmp3) && isKnownInversion(X: Cmp2, Y: Cmp4))
3690 return Builder.CreateXor(LHS: Cmp1, RHS: Cmp4);
3691 if (isKnownInversion(X: Cmp1, Y: Cmp4) && isKnownInversion(X: Cmp2, Y: Cmp3))
3692 return Builder.CreateXor(LHS: Cmp1, RHS: Cmp3);
3693
3694 return nullptr;
3695}
3696
3697/// Match \p V as "shufflevector -> bitcast" or "extractelement -> zext -> shl"
3698/// patterns, which extract vector elements and pack them in the same relative
3699/// positions.
3700///
3701/// \p Vec is the underlying vector being extracted from.
3702/// \p Mask is a bitmask identifying which packed elements are obtained from the
3703/// vector.
3704/// \p VecOffset is the vector element corresponding to index 0 of the
3705/// mask.
3706static bool matchSubIntegerPackFromVector(Value *V, Value *&Vec,
3707 int64_t &VecOffset,
3708 SmallBitVector &Mask,
3709 const DataLayout &DL) {
3710 // First try to match extractelement -> zext -> shl
3711 uint64_t VecIdx, ShlAmt;
3712 if (match(V, P: m_ShlOrSelf(L: m_ZExtOrSelf(Op: m_ExtractElt(Val: m_Value(V&: Vec),
3713 Idx: m_ConstantInt(V&: VecIdx))),
3714 R&: ShlAmt))) {
3715 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
3716 if (!VecTy)
3717 return false;
3718 auto *EltTy = dyn_cast<IntegerType>(Val: VecTy->getElementType());
3719 if (!EltTy)
3720 return false;
3721
3722 const unsigned EltBitWidth = EltTy->getBitWidth();
3723 const unsigned TargetBitWidth = V->getType()->getIntegerBitWidth();
3724 if (TargetBitWidth % EltBitWidth != 0 || ShlAmt % EltBitWidth != 0)
3725 return false;
3726 const unsigned TargetEltWidth = TargetBitWidth / EltBitWidth;
3727 const unsigned ShlEltAmt = ShlAmt / EltBitWidth;
3728
3729 const unsigned MaskIdx =
3730 DL.isLittleEndian() ? ShlEltAmt : TargetEltWidth - ShlEltAmt - 1;
3731
3732 VecOffset = static_cast<int64_t>(VecIdx) - static_cast<int64_t>(MaskIdx);
3733 Mask.resize(N: TargetEltWidth);
3734 Mask.set(MaskIdx);
3735 return true;
3736 }
3737
3738 // Now try to match a bitcasted subvector.
3739 Instruction *SrcVecI;
3740 if (!match(V, P: m_BitCast(Op: m_Instruction(I&: SrcVecI))))
3741 return false;
3742
3743 auto *SrcTy = dyn_cast<FixedVectorType>(Val: SrcVecI->getType());
3744 if (!SrcTy)
3745 return false;
3746
3747 Mask.resize(N: SrcTy->getNumElements());
3748
3749 // First check for a subvector obtained from a shufflevector.
3750 if (isa<ShuffleVectorInst>(Val: SrcVecI)) {
3751 Constant *ConstVec;
3752 ArrayRef<int> ShuffleMask;
3753 if (!match(V: SrcVecI, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Constant(C&: ConstVec),
3754 mask: m_Mask(ShuffleMask))))
3755 return false;
3756
3757 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
3758 if (!VecTy)
3759 return false;
3760
3761 const unsigned NumVecElts = VecTy->getNumElements();
3762 bool FoundVecOffset = false;
3763 for (unsigned Idx = 0; Idx < ShuffleMask.size(); ++Idx) {
3764 if (ShuffleMask[Idx] == PoisonMaskElem)
3765 return false;
3766 const unsigned ShuffleIdx = ShuffleMask[Idx];
3767 if (ShuffleIdx >= NumVecElts) {
3768 const unsigned ConstIdx = ShuffleIdx - NumVecElts;
3769 auto *ConstElt =
3770 dyn_cast<ConstantInt>(Val: ConstVec->getAggregateElement(Elt: ConstIdx));
3771 if (!ConstElt || !ConstElt->isNullValue())
3772 return false;
3773 continue;
3774 }
3775
3776 if (FoundVecOffset) {
3777 if (VecOffset + Idx != ShuffleIdx)
3778 return false;
3779 } else {
3780 if (ShuffleIdx < Idx)
3781 return false;
3782 VecOffset = ShuffleIdx - Idx;
3783 FoundVecOffset = true;
3784 }
3785 Mask.set(Idx);
3786 }
3787 return FoundVecOffset;
3788 }
3789
3790 // Check for a subvector obtained as an (insertelement V, 0, idx)
3791 uint64_t InsertIdx;
3792 if (!match(V: SrcVecI,
3793 P: m_InsertElt(Val: m_Value(V&: Vec), Elt: m_Zero(), Idx: m_ConstantInt(V&: InsertIdx))))
3794 return false;
3795
3796 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
3797 if (!VecTy)
3798 return false;
3799 VecOffset = 0;
3800 bool AlreadyInsertedMaskedElt = Mask.test(Idx: InsertIdx);
3801 Mask.set();
3802 if (!AlreadyInsertedMaskedElt)
3803 Mask.reset(Idx: InsertIdx);
3804 return true;
3805}
3806
3807/// Try to fold the join of two scalar integers whose contents are packed
3808/// elements of the same vector.
3809static Instruction *foldIntegerPackFromVector(Instruction &I,
3810 InstCombiner::BuilderTy &Builder,
3811 const DataLayout &DL) {
3812 assert(I.getOpcode() == Instruction::Or);
3813 Value *LhsVec, *RhsVec;
3814 int64_t LhsVecOffset, RhsVecOffset;
3815 SmallBitVector Mask;
3816 if (!matchSubIntegerPackFromVector(V: I.getOperand(i: 0), Vec&: LhsVec, VecOffset&: LhsVecOffset,
3817 Mask, DL))
3818 return nullptr;
3819 if (!matchSubIntegerPackFromVector(V: I.getOperand(i: 1), Vec&: RhsVec, VecOffset&: RhsVecOffset,
3820 Mask, DL))
3821 return nullptr;
3822 if (LhsVec != RhsVec || LhsVecOffset != RhsVecOffset)
3823 return nullptr;
3824
3825 // Convert into shufflevector -> bitcast;
3826 const unsigned ZeroVecIdx =
3827 cast<FixedVectorType>(Val: LhsVec->getType())->getNumElements();
3828 SmallVector<int> ShuffleMask(Mask.size(), ZeroVecIdx);
3829 for (unsigned Idx : Mask.set_bits()) {
3830 assert(LhsVecOffset + Idx >= 0);
3831 ShuffleMask[Idx] = LhsVecOffset + Idx;
3832 }
3833
3834 Value *MaskedVec = Builder.CreateShuffleVector(
3835 V1: LhsVec, V2: Constant::getNullValue(Ty: LhsVec->getType()), Mask: ShuffleMask,
3836 Name: I.getName() + ".v");
3837 return CastInst::Create(Instruction::BitCast, S: MaskedVec, Ty: I.getType());
3838}
3839
3840/// Match \p V as "lshr -> mask -> zext -> shl".
3841///
3842/// \p Int is the underlying integer being extracted from.
3843/// \p Mask is a bitmask identifying which bits of the integer are being
3844/// extracted. \p Offset identifies which bit of the result \p V corresponds to
3845/// the least significant bit of \p Int
3846static bool matchZExtedSubInteger(Value *V, Value *&Int, APInt &Mask,
3847 uint64_t &Offset, bool &IsShlNUW,
3848 bool &IsShlNSW) {
3849 Value *ShlOp0;
3850 uint64_t ShlAmt = 0;
3851 if (!match(V, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: ShlOp0), R: m_ConstantInt(V&: ShlAmt)))))
3852 return false;
3853
3854 IsShlNUW = cast<BinaryOperator>(Val: V)->hasNoUnsignedWrap();
3855 IsShlNSW = cast<BinaryOperator>(Val: V)->hasNoSignedWrap();
3856
3857 Value *ZExtOp0;
3858 if (!match(V: ShlOp0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: ZExtOp0)))))
3859 return false;
3860
3861 Value *MaskedOp0;
3862 const APInt *ShiftedMaskConst = nullptr;
3863 if (!match(V: ZExtOp0, P: m_CombineOr(Ps: m_OneUse(SubPattern: m_And(L: m_Value(V&: MaskedOp0),
3864 R: m_APInt(Res&: ShiftedMaskConst))),
3865 Ps: m_Value(V&: MaskedOp0))))
3866 return false;
3867
3868 uint64_t LShrAmt = 0;
3869 if (!match(V: MaskedOp0,
3870 P: m_CombineOr(Ps: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: Int), R: m_ConstantInt(V&: LShrAmt))),
3871 Ps: m_Value(V&: Int))))
3872 return false;
3873
3874 if (LShrAmt > ShlAmt)
3875 return false;
3876 Offset = ShlAmt - LShrAmt;
3877
3878 Mask = ShiftedMaskConst ? ShiftedMaskConst->shl(shiftAmt: LShrAmt)
3879 : APInt::getBitsSetFrom(
3880 numBits: Int->getType()->getScalarSizeInBits(), loBit: LShrAmt);
3881
3882 return true;
3883}
3884
3885/// Try to fold the join of two scalar integers whose bits are unpacked and
3886/// zexted from the same source integer.
3887static Value *foldIntegerRepackThroughZExt(Value *Lhs, Value *Rhs,
3888 InstCombiner::BuilderTy &Builder) {
3889
3890 Value *LhsInt, *RhsInt;
3891 APInt LhsMask, RhsMask;
3892 uint64_t LhsOffset, RhsOffset;
3893 bool IsLhsShlNUW, IsLhsShlNSW, IsRhsShlNUW, IsRhsShlNSW;
3894 if (!matchZExtedSubInteger(V: Lhs, Int&: LhsInt, Mask&: LhsMask, Offset&: LhsOffset, IsShlNUW&: IsLhsShlNUW,
3895 IsShlNSW&: IsLhsShlNSW))
3896 return nullptr;
3897 if (!matchZExtedSubInteger(V: Rhs, Int&: RhsInt, Mask&: RhsMask, Offset&: RhsOffset, IsShlNUW&: IsRhsShlNUW,
3898 IsShlNSW&: IsRhsShlNSW))
3899 return nullptr;
3900 if (LhsInt != RhsInt || LhsOffset != RhsOffset)
3901 return nullptr;
3902
3903 APInt Mask = LhsMask | RhsMask;
3904
3905 Type *DestTy = Lhs->getType();
3906 Value *Res = Builder.CreateShl(
3907 LHS: Builder.CreateZExt(
3908 V: Builder.CreateAnd(LHS: LhsInt, RHS: Mask, Name: LhsInt->getName() + ".mask"), DestTy,
3909 Name: LhsInt->getName() + ".zext"),
3910 RHS: ConstantInt::get(Ty: DestTy, V: LhsOffset), Name: "", HasNUW: IsLhsShlNUW && IsRhsShlNUW,
3911 HasNSW: IsLhsShlNSW && IsRhsShlNSW);
3912 Res->takeName(V: Lhs);
3913 return Res;
3914}
3915
3916// A decomposition of ((X & Mask) * Factor). The NUW / NSW bools
3917// track these properities for preservation. Note that we can decompose
3918// equivalent select form of this expression (e.g. (!(X & Mask) ? 0 : Mask *
3919// Factor))
3920struct DecomposedBitMaskMul {
3921 Value *X;
3922 APInt Factor;
3923 APInt Mask;
3924 bool NUW;
3925 bool NSW;
3926
3927 bool isCombineableWith(const DecomposedBitMaskMul Other) {
3928 return X == Other.X && !Mask.intersects(RHS: Other.Mask) &&
3929 Factor == Other.Factor;
3930 }
3931};
3932
3933static std::optional<DecomposedBitMaskMul> matchBitmaskMul(Value *V) {
3934 Instruction *Op = dyn_cast<Instruction>(Val: V);
3935 if (!Op)
3936 return std::nullopt;
3937
3938 // Decompose (A & N) * C) into BitMaskMul
3939 Value *Original = nullptr;
3940 const APInt *Mask = nullptr;
3941 const APInt *MulConst = nullptr;
3942 if (match(V: Op, P: m_Mul(L: m_And(L: m_Value(V&: Original), R: m_APInt(Res&: Mask)),
3943 R: m_APInt(Res&: MulConst)))) {
3944 if (MulConst->isZero() || Mask->isZero())
3945 return std::nullopt;
3946
3947 return std::optional<DecomposedBitMaskMul>(
3948 {.X: Original, .Factor: *MulConst, .Mask: *Mask,
3949 .NUW: cast<BinaryOperator>(Val: Op)->hasNoUnsignedWrap(),
3950 .NSW: cast<BinaryOperator>(Val: Op)->hasNoSignedWrap()});
3951 }
3952
3953 Value *Cond = nullptr;
3954 const APInt *EqZero = nullptr, *NeZero = nullptr;
3955
3956 // Decompose ((A & N) ? 0 : N * C) into BitMaskMul
3957 if (match(V: Op, P: m_Select(C: m_Value(V&: Cond), L: m_APInt(Res&: EqZero), R: m_APInt(Res&: NeZero)))) {
3958 auto ICmpDecompose =
3959 decomposeBitTest(Cond, /*LookThroughTrunc=*/true,
3960 /*AllowNonZeroC=*/false, /*DecomposeBitMask=*/DecomposeAnd: true);
3961 if (!ICmpDecompose.has_value())
3962 return std::nullopt;
3963
3964 // decomposeBitTest may provide a scalar bit test for a vector select.
3965 // Ensure the types match.
3966 if (ICmpDecompose->X->getType() != V->getType())
3967 return std::nullopt;
3968
3969 assert(ICmpInst::isEquality(ICmpDecompose->Pred) &&
3970 ICmpDecompose->C.isZero());
3971
3972 if (ICmpDecompose->Pred == ICmpInst::ICMP_NE)
3973 std::swap(a&: EqZero, b&: NeZero);
3974
3975 if (!EqZero->isZero() || NeZero->isZero())
3976 return std::nullopt;
3977
3978 if (!ICmpDecompose->Mask.isPowerOf2() || ICmpDecompose->Mask.isZero())
3979 return std::nullopt;
3980
3981 if (!NeZero->urem(RHS: ICmpDecompose->Mask).isZero())
3982 return std::nullopt;
3983
3984 return std::optional<DecomposedBitMaskMul>(
3985 {.X: ICmpDecompose->X, .Factor: NeZero->udiv(RHS: ICmpDecompose->Mask),
3986 .Mask: ICmpDecompose->Mask, /*NUW=*/false, /*NSW=*/false});
3987 }
3988
3989 return std::nullopt;
3990}
3991
3992/// (A & N) * C + (A & M) * C -> (A & (N + M)) & C
3993/// This also accepts the equivalent select form of (A & N) * C
3994/// expressions i.e. !(A & N) ? 0 : N * C)
3995static Value *foldBitmaskMul(Value *Op0, Value *Op1,
3996 InstCombiner::BuilderTy &Builder) {
3997 auto Decomp1 = matchBitmaskMul(V: Op1);
3998 if (!Decomp1)
3999 return nullptr;
4000
4001 auto Decomp0 = matchBitmaskMul(V: Op0);
4002 if (!Decomp0)
4003 return nullptr;
4004
4005 if (Decomp0->isCombineableWith(Other: *Decomp1)) {
4006 Value *NewAnd = Builder.CreateAnd(
4007 LHS: Decomp0->X,
4008 RHS: ConstantInt::get(Ty: Decomp0->X->getType(), V: Decomp0->Mask + Decomp1->Mask));
4009
4010 return Builder.CreateMul(
4011 LHS: NewAnd, RHS: ConstantInt::get(Ty: NewAnd->getType(), V: Decomp1->Factor), Name: "",
4012 HasNUW: Decomp0->NUW && Decomp1->NUW, HasNSW: Decomp0->NSW && Decomp1->NSW);
4013 }
4014
4015 return nullptr;
4016}
4017
4018Value *InstCombinerImpl::foldDisjointOr(Value *LHS, Value *RHS) {
4019 if (Value *Res = foldBitmaskMul(Op0: LHS, Op1: RHS, Builder))
4020 return Res;
4021 if (Value *Res = foldIntegerRepackThroughZExt(Lhs: LHS, Rhs: RHS, Builder))
4022 return Res;
4023
4024 return nullptr;
4025}
4026
4027Value *InstCombinerImpl::reassociateDisjointOr(Value *LHS, Value *RHS) {
4028
4029 Value *X, *Y;
4030 if (match(V: RHS, P: m_OneUse(SubPattern: m_DisjointOr(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
4031 if (Value *Res = foldDisjointOr(LHS, RHS: X))
4032 return Builder.CreateDisjointOr(LHS: Res, RHS: Y);
4033 if (Value *Res = foldDisjointOr(LHS, RHS: Y))
4034 return Builder.CreateDisjointOr(LHS: Res, RHS: X);
4035 }
4036
4037 if (match(V: LHS, P: m_OneUse(SubPattern: m_DisjointOr(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
4038 if (Value *Res = foldDisjointOr(LHS: X, RHS))
4039 return Builder.CreateDisjointOr(LHS: Res, RHS: Y);
4040 if (Value *Res = foldDisjointOr(LHS: Y, RHS))
4041 return Builder.CreateDisjointOr(LHS: Res, RHS: X);
4042 }
4043
4044 return nullptr;
4045}
4046
4047/// Fold Res, Overflow = (umul.with.overflow x c1); (or Overflow (ugt Res c2))
4048/// --> (ugt x (c2/c1)). This code checks whether a multiplication of two
4049/// unsigned numbers (one is a constant) is mathematically greater than a
4050/// second constant.
4051static Value *foldOrUnsignedUMulOverflowICmp(BinaryOperator &I,
4052 InstCombiner::BuilderTy &Builder,
4053 const DataLayout &DL) {
4054 Value *WOV, *X;
4055 const APInt *C1, *C2;
4056 if (match(V: &I,
4057 P: m_c_Or(L: m_ExtractValue<1>(
4058 V: m_Value(V&: WOV, P: m_Intrinsic<Intrinsic::umul_with_overflow>(
4059 Ops: m_Value(V&: X), Ops: m_APInt(Res&: C1)))),
4060 R: m_OneUse(SubPattern: m_SpecificCmp(MatchPred: ICmpInst::ICMP_UGT,
4061 L: m_ExtractValue<0>(V: m_Deferred(V: WOV)),
4062 R: m_APInt(Res&: C2))))) &&
4063 !C1->isZero()) {
4064 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: C2->udiv(RHS: *C1));
4065 return Builder.CreateICmp(P: ICmpInst::ICMP_UGT, LHS: X, RHS: NewC);
4066 }
4067 return nullptr;
4068}
4069
4070/// Fold select(X >s 0, 0, -X) | smax(X, 0) --> abs(X)
4071/// select(X <s 0, -X, 0) | smax(X, 0) --> abs(X)
4072static Value *FoldOrOfSelectSmaxToAbs(BinaryOperator &I,
4073 InstCombiner::BuilderTy &Builder) {
4074 Value *X;
4075 Value *Sel;
4076 if (match(V: &I,
4077 P: m_c_Or(L: m_Value(V&: Sel), R: m_OneUse(SubPattern: m_SMax(Op0: m_Value(V&: X), Op1: m_ZeroInt()))))) {
4078 auto NegX = m_Neg(V: m_Specific(V: X));
4079 if (match(V: Sel, P: m_Select(C: m_SpecificICmp(MatchPred: ICmpInst::ICMP_SGT, L: m_Specific(V: X),
4080 R: m_ZeroInt()),
4081 L: m_ZeroInt(), R: NegX)) ||
4082 match(V: Sel, P: m_Select(C: m_SpecificICmp(MatchPred: ICmpInst::ICMP_SLT, L: m_Specific(V: X),
4083 R: m_ZeroInt()),
4084 L: NegX, R: m_ZeroInt())))
4085 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: X,
4086 RHS: Builder.getFalse());
4087 }
4088 return nullptr;
4089}
4090
4091Instruction *InstCombinerImpl::FoldOrOfLogicalAnds(Value *Op0, Value *Op1) {
4092 Value *C, *A, *B;
4093 // (C && A) || (!C && B)
4094 // (C && A) || (B && !C)
4095 // (A && C) || (!C && B)
4096 // (A && C) || (B && !C) (may require freeze)
4097 //
4098 // => select C, A, B
4099 if (match(V: Op1, P: m_c_LogicalAnd(L: m_Not(V: m_Value(V&: C)), R: m_Value(V&: B))) &&
4100 match(V: Op0, P: m_c_LogicalAnd(L: m_Specific(V: C), R: m_Value(V&: A)))) {
4101 auto *SelOp0 = dyn_cast<SelectInst>(Val: Op0);
4102 auto *SelOp1 = dyn_cast<SelectInst>(Val: Op1);
4103
4104 bool MayNeedFreeze = SelOp0 && SelOp1 &&
4105 match(V: SelOp1->getTrueValue(),
4106 P: m_Not(V: m_Specific(V: SelOp0->getTrueValue())));
4107 if (MayNeedFreeze)
4108 C = Builder.CreateFreeze(V: C);
4109 if (!ProfcheckDisableMetadataFixes) {
4110 Value *C2 = nullptr, *A2 = nullptr, *B2 = nullptr;
4111 if (match(V: Op0, P: m_LogicalAnd(L: m_Specific(V: C), R: m_Value(V&: A2))) && SelOp0) {
4112 return SelectInst::Create(C, S1: A, S2: B, NameStr: "", InsertBefore: nullptr, MDFrom: SelOp0);
4113 } else if (match(V: Op1, P: m_LogicalAnd(L: m_Not(V: m_Value(V&: C2)), R: m_Value(V&: B2))) &&
4114 SelOp1) {
4115 SelectInst *NewSI = SelectInst::Create(C, S1: A, S2: B, NameStr: "", InsertBefore: nullptr, MDFrom: SelOp1);
4116 NewSI->swapProfMetadata();
4117 return NewSI;
4118 } else {
4119 return createSelectInstWithUnknownProfile(C, S1: A, S2: B);
4120 }
4121 }
4122 return SelectInst::Create(C, S1: A, S2: B);
4123 }
4124
4125 // (!C && A) || (C && B)
4126 // (A && !C) || (C && B)
4127 // (!C && A) || (B && C)
4128 // (A && !C) || (B && C) (may require freeze)
4129 //
4130 // => select C, B, A
4131 if (match(V: Op0, P: m_c_LogicalAnd(L: m_Not(V: m_Value(V&: C)), R: m_Value(V&: A))) &&
4132 match(V: Op1, P: m_c_LogicalAnd(L: m_Specific(V: C), R: m_Value(V&: B)))) {
4133 auto *SelOp0 = dyn_cast<SelectInst>(Val: Op0);
4134 auto *SelOp1 = dyn_cast<SelectInst>(Val: Op1);
4135 bool MayNeedFreeze = SelOp0 && SelOp1 &&
4136 match(V: SelOp0->getTrueValue(),
4137 P: m_Not(V: m_Specific(V: SelOp1->getTrueValue())));
4138 if (MayNeedFreeze)
4139 C = Builder.CreateFreeze(V: C);
4140 if (!ProfcheckDisableMetadataFixes) {
4141 Value *C2 = nullptr, *A2 = nullptr, *B2 = nullptr;
4142 if (match(V: Op0, P: m_LogicalAnd(L: m_Not(V: m_Value(V&: C2)), R: m_Value(V&: A2))) && SelOp0) {
4143 SelectInst *NewSI = SelectInst::Create(C, S1: B, S2: A, NameStr: "", InsertBefore: nullptr, MDFrom: SelOp0);
4144 NewSI->swapProfMetadata();
4145 return NewSI;
4146 } else if (match(V: Op1, P: m_LogicalAnd(L: m_Specific(V: C), R: m_Value(V&: B2))) &&
4147 SelOp1) {
4148 return SelectInst::Create(C, S1: B, S2: A, NameStr: "", InsertBefore: nullptr, MDFrom: SelOp1);
4149 } else {
4150 return createSelectInstWithUnknownProfile(C, S1: B, S2: A);
4151 }
4152 }
4153 return SelectInst::Create(C, S1: B, S2: A);
4154 }
4155
4156 return nullptr;
4157}
4158
4159// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
4160// here. We should standardize that construct where it is needed or choose some
4161// other way to ensure that commutated variants of patterns are not missed.
4162Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
4163 if (Value *V = simplifyOrInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
4164 Q: SQ.getWithInstruction(I: &I)))
4165 return replaceInstUsesWith(I, V);
4166
4167 if (SimplifyAssociativeOrCommutative(I))
4168 return &I;
4169
4170 if (Instruction *X = foldVectorBinop(Inst&: I))
4171 return X;
4172
4173 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
4174 return Phi;
4175
4176 // See if we can simplify any instructions used by the instruction whose sole
4177 // purpose is to compute bits we don't care about.
4178 if (SimplifyDemandedInstructionBits(Inst&: I))
4179 return &I;
4180
4181 // Do this before using distributive laws to catch simple and/or/not patterns.
4182 if (Instruction *Xor = foldOrToXor(I, Builder))
4183 return Xor;
4184
4185 if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
4186 return X;
4187
4188 if (Instruction *X = foldIntegerPackFromVector(I, Builder, DL))
4189 return X;
4190
4191 // (A & B) | (C & D) -> A ^ D where A == ~C && B == ~D
4192 // (A & B) | (C & D) -> A ^ C where A == ~D && B == ~C
4193 if (Value *V = foldOrOfInversions(I, Builder))
4194 return replaceInstUsesWith(I, V);
4195
4196 // (A&B)|(A&C) -> A&(B|C) etc
4197 if (Value *V = foldUsingDistributiveLaws(I))
4198 return replaceInstUsesWith(I, V);
4199
4200 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4201 Type *Ty = I.getType();
4202 if (Ty->isIntOrIntVectorTy(BitWidth: 1)) {
4203 if (auto *SI0 = dyn_cast<SelectInst>(Val: Op0)) {
4204 if (auto *R =
4205 foldAndOrOfSelectUsingImpliedCond(Op: Op1, SI&: *SI0, /* IsAnd */ false))
4206 return R;
4207 }
4208 if (auto *SI1 = dyn_cast<SelectInst>(Val: Op1)) {
4209 if (auto *R =
4210 foldAndOrOfSelectUsingImpliedCond(Op: Op0, SI&: *SI1, /* IsAnd */ false))
4211 return R;
4212 }
4213 }
4214
4215 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
4216 return FoldedLogic;
4217
4218 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Op&: I))
4219 return FoldedLogic;
4220
4221 if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
4222 /*MatchBitReversals*/ true))
4223 return BitOp;
4224
4225 if (Instruction *Funnel = matchFunnelShift(Or&: I, IC&: *this))
4226 return Funnel;
4227
4228 if (Value *Concat = matchOrConcat(Or&: I, Builder))
4229 return replaceInstUsesWith(I, V: Concat);
4230
4231 if (Instruction *R = foldBinOpShiftWithShift(I))
4232 return R;
4233
4234 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &I))
4235 return R;
4236
4237 if (cast<PossiblyDisjointInst>(Val&: I).isDisjoint()) {
4238 if (Instruction *R =
4239 foldAddLikeCommutative(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
4240 /*NSW=*/true, /*NUW=*/true))
4241 return R;
4242 if (Instruction *R =
4243 foldAddLikeCommutative(LHS: I.getOperand(i_nocapture: 1), RHS: I.getOperand(i_nocapture: 0),
4244 /*NSW=*/true, /*NUW=*/true))
4245 return R;
4246
4247 if (Value *Res = foldDisjointOr(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1)))
4248 return replaceInstUsesWith(I, V: Res);
4249
4250 if (Value *Res = reassociateDisjointOr(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1)))
4251 return replaceInstUsesWith(I, V: Res);
4252 }
4253
4254 Value *X, *Y;
4255 const APInt *CV;
4256 if (match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: X), R: m_APInt(Res&: CV))), R: m_Value(V&: Y))) &&
4257 !CV->isAllOnes() && MaskedValueIsZero(V: Y, Mask: *CV, CxtI: &I)) {
4258 // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
4259 // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
4260 Value *Or = Builder.CreateOr(LHS: X, RHS: Y);
4261 return BinaryOperator::CreateXor(V1: Or, V2: ConstantInt::get(Ty, V: *CV));
4262 }
4263
4264 // If the operands have no common bits set:
4265 // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
4266 if (match(V: &I, P: m_c_DisjointOr(L: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))),
4267 R: m_Deferred(V: X)))) {
4268 Value *IncrementY = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
4269 return BinaryOperator::CreateMul(V1: X, V2: IncrementY);
4270 }
4271
4272 // Canonicalization to achieve lowering to Bit Manipulation Instructions (BMI)
4273 // ~X | (X-1) => ~(X & -X)
4274 Value *Op;
4275 if (match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_Not(V: m_Value(V&: Op))),
4276 R: m_OneUse(SubPattern: m_Add(L: m_Deferred(V: Op), R: m_AllOnes()))))) {
4277 Value *NegX = Builder.CreateNeg(V: Op);
4278 Value *And = Builder.CreateAnd(LHS: Op, RHS: NegX);
4279 return BinaryOperator::CreateNot(Op: And);
4280 }
4281
4282 // (C && A) || (C && B) => select C, A, B (and similar cases)
4283 //
4284 // Note: This is the same transformation used in `foldSelectOfBools`,
4285 // except that it's an `or` instead of `select`.
4286 if (I.getType()->isIntOrIntVectorTy(BitWidth: 1) &&
4287 (Op0->hasOneUse() || Op1->hasOneUse())) {
4288 if (Instruction *V = FoldOrOfLogicalAnds(Op0, Op1)) {
4289 return V;
4290 }
4291 }
4292
4293 // (A & C) | (B & D)
4294 Value *A, *B, *C, *D;
4295 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: C))) &&
4296 match(V: Op1, P: m_And(L: m_Value(V&: B), R: m_Value(V&: D)))) {
4297
4298 // (A & C0) | (B & C1)
4299 const APInt *C0, *C1;
4300 if (match(V: C, P: m_APInt(Res&: C0)) && match(V: D, P: m_APInt(Res&: C1))) {
4301 Value *X;
4302 if (*C0 == ~*C1) {
4303 // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
4304 if (match(V: A, P: m_c_Or(L: m_Value(V&: X), R: m_Specific(V: B))))
4305 return BinaryOperator::CreateOr(V1: Builder.CreateAnd(LHS: X, RHS: *C0), V2: B);
4306 // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
4307 if (match(V: B, P: m_c_Or(L: m_Specific(V: A), R: m_Value(V&: X))))
4308 return BinaryOperator::CreateOr(V1: Builder.CreateAnd(LHS: X, RHS: *C1), V2: A);
4309
4310 // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
4311 if (match(V: A, P: m_c_Xor(L: m_Value(V&: X), R: m_Specific(V: B))))
4312 return BinaryOperator::CreateXor(V1: Builder.CreateAnd(LHS: X, RHS: *C0), V2: B);
4313 // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
4314 if (match(V: B, P: m_c_Xor(L: m_Specific(V: A), R: m_Value(V&: X))))
4315 return BinaryOperator::CreateXor(V1: Builder.CreateAnd(LHS: X, RHS: *C1), V2: A);
4316 }
4317
4318 if ((*C0 & *C1).isZero()) {
4319 // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
4320 // iff (C0 & C1) == 0 and (X & ~C0) == 0
4321 if (match(V: A, P: m_c_Or(L: m_Value(V&: X), R: m_Specific(V: B))) &&
4322 MaskedValueIsZero(V: X, Mask: ~*C0, CxtI: &I)) {
4323 Constant *C01 = ConstantInt::get(Ty, V: *C0 | *C1);
4324 return BinaryOperator::CreateAnd(V1: A, V2: C01);
4325 }
4326 // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
4327 // iff (C0 & C1) == 0 and (X & ~C1) == 0
4328 if (match(V: B, P: m_c_Or(L: m_Value(V&: X), R: m_Specific(V: A))) &&
4329 MaskedValueIsZero(V: X, Mask: ~*C1, CxtI: &I)) {
4330 Constant *C01 = ConstantInt::get(Ty, V: *C0 | *C1);
4331 return BinaryOperator::CreateAnd(V1: B, V2: C01);
4332 }
4333 // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
4334 // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
4335 const APInt *C2, *C3;
4336 if (match(V: A, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: C2))) &&
4337 match(V: B, P: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C3))) &&
4338 (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
4339 Value *Or = Builder.CreateOr(LHS: X, RHS: *C2 | *C3, Name: "bitfield");
4340 Constant *C01 = ConstantInt::get(Ty, V: *C0 | *C1);
4341 return BinaryOperator::CreateAnd(V1: Or, V2: C01);
4342 }
4343 }
4344 }
4345
4346 // Don't try to form a select if it's unlikely that we'll get rid of at
4347 // least one of the operands. A select is generally more expensive than the
4348 // 'or' that it is replacing.
4349 if (Op0->hasOneUse() || Op1->hasOneUse()) {
4350 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
4351 if (Value *V = matchSelectFromAndOr(A, B: C, C: B, D))
4352 return replaceInstUsesWith(I, V);
4353 if (Value *V = matchSelectFromAndOr(A, B: C, C: D, D: B))
4354 return replaceInstUsesWith(I, V);
4355 if (Value *V = matchSelectFromAndOr(A: C, B: A, C: B, D))
4356 return replaceInstUsesWith(I, V);
4357 if (Value *V = matchSelectFromAndOr(A: C, B: A, C: D, D: B))
4358 return replaceInstUsesWith(I, V);
4359 if (Value *V = matchSelectFromAndOr(A: B, B: D, C: A, D: C))
4360 return replaceInstUsesWith(I, V);
4361 if (Value *V = matchSelectFromAndOr(A: B, B: D, C, D: A))
4362 return replaceInstUsesWith(I, V);
4363 if (Value *V = matchSelectFromAndOr(A: D, B, C: A, D: C))
4364 return replaceInstUsesWith(I, V);
4365 if (Value *V = matchSelectFromAndOr(A: D, B, C, D: A))
4366 return replaceInstUsesWith(I, V);
4367 }
4368 }
4369
4370 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: C))) &&
4371 match(V: Op1, P: m_Not(V: m_Or(L: m_Value(V&: B), R: m_Value(V&: D)))) &&
4372 (Op0->hasOneUse() || Op1->hasOneUse())) {
4373 // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
4374 if (Value *V = matchSelectFromAndOr(A, B: C, C: B, D, InvertFalseVal: true))
4375 return replaceInstUsesWith(I, V);
4376 if (Value *V = matchSelectFromAndOr(A, B: C, C: D, D: B, InvertFalseVal: true))
4377 return replaceInstUsesWith(I, V);
4378 if (Value *V = matchSelectFromAndOr(A: C, B: A, C: B, D, InvertFalseVal: true))
4379 return replaceInstUsesWith(I, V);
4380 if (Value *V = matchSelectFromAndOr(A: C, B: A, C: D, D: B, InvertFalseVal: true))
4381 return replaceInstUsesWith(I, V);
4382 }
4383
4384 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
4385 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))))
4386 if (match(V: Op1,
4387 P: m_c_Xor(L: m_c_Xor(L: m_Specific(V: B), R: m_Value(V&: C)), R: m_Specific(V: A))) ||
4388 match(V: Op1, P: m_c_Xor(L: m_c_Xor(L: m_Specific(V: A), R: m_Value(V&: C)), R: m_Specific(V: B))))
4389 return BinaryOperator::CreateOr(V1: Op0, V2: C);
4390
4391 // ((B ^ C) ^ A) | (A ^ B) -> (A ^ B) | C
4392 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))))
4393 if (match(V: Op0,
4394 P: m_c_Xor(L: m_c_Xor(L: m_Specific(V: B), R: m_Value(V&: C)), R: m_Specific(V: A))) ||
4395 match(V: Op0, P: m_c_Xor(L: m_c_Xor(L: m_Specific(V: A), R: m_Value(V&: C)), R: m_Specific(V: B))))
4396 return BinaryOperator::CreateOr(V1: Op1, V2: C);
4397
4398 if (Instruction *DeMorgan = matchDeMorgansLaws(I, IC&: *this))
4399 return DeMorgan;
4400
4401 // Canonicalize xor to the RHS.
4402 bool SwappedForXor = false;
4403 if (match(V: Op0, P: m_Xor(L: m_Value(), R: m_Value()))) {
4404 std::swap(a&: Op0, b&: Op1);
4405 SwappedForXor = true;
4406 }
4407
4408 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
4409 // (A | ?) | (A ^ B) --> (A | ?) | B
4410 // (B | ?) | (A ^ B) --> (B | ?) | A
4411 if (match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Value())))
4412 return BinaryOperator::CreateOr(V1: Op0, V2: B);
4413 if (match(V: Op0, P: m_c_Or(L: m_Specific(V: B), R: m_Value())))
4414 return BinaryOperator::CreateOr(V1: Op0, V2: A);
4415
4416 // (A & B) | (A ^ B) --> A | B
4417 // (B & A) | (A ^ B) --> A | B
4418 if (match(V: Op0, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
4419 return BinaryOperator::CreateOr(V1: A, V2: B);
4420
4421 // ~A | (A ^ B) --> ~(A & B)
4422 // ~B | (A ^ B) --> ~(A & B)
4423 // The swap above should always make Op0 the 'not'.
4424 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
4425 (match(V: Op0, P: m_Not(V: m_Specific(V: A))) || match(V: Op0, P: m_Not(V: m_Specific(V: B)))))
4426 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: A, RHS: B));
4427
4428 // Same as above, but peek through an 'and' to the common operand:
4429 // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
4430 // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
4431 Instruction *And;
4432 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
4433 match(V: Op0,
4434 P: m_Not(V: m_Instruction(I&: And, P: m_c_And(L: m_Specific(V: A), R: m_Value())))))
4435 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: And, RHS: B));
4436 if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
4437 match(V: Op0,
4438 P: m_Not(V: m_Instruction(I&: And, P: m_c_And(L: m_Specific(V: B), R: m_Value())))))
4439 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: And, RHS: A));
4440
4441 // (~A | C) | (A ^ B) --> ~(A & B) | C
4442 // (~B | C) | (A ^ B) --> ~(A & B) | C
4443 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4444 (match(V: Op0, P: m_c_Or(L: m_Not(V: m_Specific(V: A)), R: m_Value(V&: C))) ||
4445 match(V: Op0, P: m_c_Or(L: m_Not(V: m_Specific(V: B)), R: m_Value(V&: C))))) {
4446 Value *Nand = Builder.CreateNot(V: Builder.CreateAnd(LHS: A, RHS: B), Name: "nand");
4447 return BinaryOperator::CreateOr(V1: Nand, V2: C);
4448 }
4449 }
4450
4451 if (SwappedForXor)
4452 std::swap(a&: Op0, b&: Op1);
4453
4454 if (Value *Res =
4455 foldBooleanAndOr(LHS: Op0, RHS: Op1, I, /*IsAnd=*/false, /*IsLogical=*/false))
4456 return replaceInstUsesWith(I, V: Res);
4457
4458 if (match(V: Op1, P: m_OneUse(SubPattern: m_LogicalOr(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
4459 bool IsLogical = isa<SelectInst>(Val: Op1);
4460 if (auto *V = reassociateBooleanAndOr(LHS: Op0, X, Y, I, /*IsAnd=*/false,
4461 /*RHSIsLogical=*/IsLogical))
4462 return replaceInstUsesWith(I, V);
4463 }
4464 if (match(V: Op0, P: m_OneUse(SubPattern: m_LogicalOr(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
4465 bool IsLogical = isa<SelectInst>(Val: Op0);
4466 if (auto *V = reassociateBooleanAndOr(LHS: Op1, X, Y, I, /*IsAnd=*/false,
4467 /*RHSIsLogical=*/IsLogical))
4468 return replaceInstUsesWith(I, V);
4469 }
4470
4471 if (Instruction *FoldedFCmps = reassociateFCmps(BO&: I, Builder))
4472 return FoldedFCmps;
4473
4474 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
4475 return CastedOr;
4476
4477 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
4478 return Sel;
4479
4480 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
4481 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
4482 // with binop identity constant. But creating a select with non-constant
4483 // arm may not be reversible due to poison semantics. Is that a good
4484 // canonicalization?
4485 if (match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: A))), R: m_Value(V&: B))) &&
4486 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
4487 return createSelectInstWithUnknownProfile(
4488 C: A, S1: ConstantInt::getAllOnesValue(Ty), S2: B);
4489
4490 // Note: If we've gotten to the point of visiting the outer OR, then the
4491 // inner one couldn't be simplified. If it was a constant, then it won't
4492 // be simplified by a later pass either, so we try swapping the inner/outer
4493 // ORs in the hopes that we'll be able to simplify it this way.
4494 // (X|C) | V --> (X|V) | C
4495 // Pass the disjoint flag in the following two patterns:
4496 // 1. or-disjoint (or-disjoint X, C), V -->
4497 // or-disjoint (or-disjoint X, V), C
4498 //
4499 // 2. or-disjoint (or X, C), V -->
4500 // or (or-disjoint X, V), C
4501 ConstantInt *CI;
4502 if (Op0->hasOneUse() && !match(V: Op1, P: m_ConstantInt()) &&
4503 match(V: Op0, P: m_Or(L: m_Value(V&: A), R: m_ConstantInt(CI)))) {
4504 bool IsDisjointOuter = cast<PossiblyDisjointInst>(Val&: I).isDisjoint();
4505 bool IsDisjointInner = cast<PossiblyDisjointInst>(Val: Op0)->isDisjoint();
4506 Value *Inner = Builder.CreateOr(LHS: A, RHS: Op1, Name: "", /*IsDisjoint=*/IsDisjointOuter);
4507 Inner->takeName(V: Op0);
4508 return IsDisjointOuter && IsDisjointInner
4509 ? BinaryOperator::CreateDisjointOr(V1: Inner, V2: CI)
4510 : BinaryOperator::CreateOr(V1: Inner, V2: CI);
4511 }
4512
4513 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
4514 // Since this OR statement hasn't been optimized further yet, we hope
4515 // that this transformation will allow the new ORs to be optimized.
4516 {
4517 Value *X = nullptr, *Y = nullptr;
4518 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4519 match(V: Op0, P: m_Select(C: m_Value(V&: X), L: m_Value(V&: A), R: m_Value(V&: B))) &&
4520 match(V: Op1, P: m_Select(C: m_Value(V&: Y), L: m_Value(V&: C), R: m_Value(V&: D))) && X == Y) {
4521 Value *orTrue = Builder.CreateOr(LHS: A, RHS: C);
4522 Value *orFalse = Builder.CreateOr(LHS: B, RHS: D);
4523 return SelectInst::Create(C: X, S1: orTrue, S2: orFalse);
4524 }
4525 }
4526
4527 // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X) --> X s> Y ? -1 : X.
4528 {
4529 Value *X, *Y;
4530 if (match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_AShr(
4531 L: m_NSWSub(L: m_Value(V&: Y), R: m_Value(V&: X)),
4532 R: m_SpecificInt(V: Ty->getScalarSizeInBits() - 1))),
4533 R: m_Deferred(V: X)))) {
4534 Value *NewICmpInst = Builder.CreateICmpSGT(LHS: X, RHS: Y);
4535 Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
4536 return createSelectInstWithUnknownProfile(C: NewICmpInst, S1: AllOnes, S2: X);
4537 }
4538 }
4539
4540 {
4541 // ((A & B) ^ A) | ((A & B) ^ B) -> A ^ B
4542 // (A ^ (A & B)) | (B ^ (A & B)) -> A ^ B
4543 // ((A & B) ^ B) | ((A & B) ^ A) -> A ^ B
4544 // (B ^ (A & B)) | (A ^ (A & B)) -> A ^ B
4545 const auto TryXorOpt = [&](Value *Lhs, Value *Rhs) -> Instruction * {
4546 if (match(V: Lhs, P: m_c_Xor(L: m_And(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_Deferred(V: A))) &&
4547 match(V: Rhs,
4548 P: m_c_Xor(L: m_And(L: m_Specific(V: A), R: m_Specific(V: B)), R: m_Specific(V: B)))) {
4549 return BinaryOperator::CreateXor(V1: A, V2: B);
4550 }
4551 return nullptr;
4552 };
4553
4554 if (Instruction *Result = TryXorOpt(Op0, Op1))
4555 return Result;
4556 if (Instruction *Result = TryXorOpt(Op1, Op0))
4557 return Result;
4558 }
4559
4560 if (Instruction *V =
4561 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
4562 return V;
4563
4564 CmpPredicate Pred;
4565 Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
4566 // Check if the OR weakens the overflow condition for umul.with.overflow by
4567 // treating any non-zero result as overflow. In that case, we overflow if both
4568 // umul.with.overflow operands are != 0, as in that case the result can only
4569 // be 0, iff the multiplication overflows.
4570 if (match(V: &I, P: m_c_Or(L: m_Value(V&: Ov, P: m_ExtractValue<1>(V: m_Value(V&: UMulWithOv))),
4571 R: m_Value(V&: MulIsNotZero,
4572 P: m_SpecificICmp(
4573 MatchPred: ICmpInst::ICMP_NE,
4574 L: m_Value(V&: Mul, P: m_ExtractValue<0>(
4575 V: m_Deferred(V: UMulWithOv))),
4576 R: m_ZeroInt())))) &&
4577 (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse()))) {
4578 Value *A, *B;
4579 if (match(V: UMulWithOv, P: m_Intrinsic<Intrinsic::umul_with_overflow>(
4580 Ops: m_Value(V&: A), Ops: m_Value(V&: B)))) {
4581 Value *NotNullA = Builder.CreateIsNotNull(Arg: A);
4582 Value *NotNullB = Builder.CreateIsNotNull(Arg: B);
4583 return BinaryOperator::CreateAnd(V1: NotNullA, V2: NotNullB);
4584 }
4585 }
4586
4587 /// Res, Overflow = xxx_with_overflow X, C1
4588 /// Try to canonicalize the pattern "Overflow | icmp pred Res, C2" into
4589 /// "Overflow | icmp pred X, C2 +/- C1".
4590 const WithOverflowInst *WO;
4591 const Value *WOV;
4592 const APInt *C1, *C2;
4593 if (match(V: &I, P: m_c_Or(L: m_Value(V&: Ov, P: m_ExtractValue<1>(
4594 V: m_Value(V&: WOV, P: m_WithOverflowInst(I&: WO)))),
4595 R: m_OneUse(SubPattern: m_ICmp(Pred, L: m_ExtractValue<0>(V: m_Deferred(V: WOV)),
4596 R: m_APInt(Res&: C2))))) &&
4597 (WO->getBinaryOp() == Instruction::Add ||
4598 WO->getBinaryOp() == Instruction::Sub) &&
4599 (ICmpInst::isEquality(P: Pred) ||
4600 WO->isSigned() == ICmpInst::isSigned(Pred)) &&
4601 match(V: WO->getRHS(), P: m_APInt(Res&: C1))) {
4602 bool Overflow;
4603 APInt NewC = WO->getBinaryOp() == Instruction::Add
4604 ? (ICmpInst::isSigned(Pred) ? C2->ssub_ov(RHS: *C1, Overflow)
4605 : C2->usub_ov(RHS: *C1, Overflow))
4606 : (ICmpInst::isSigned(Pred) ? C2->sadd_ov(RHS: *C1, Overflow)
4607 : C2->uadd_ov(RHS: *C1, Overflow));
4608 if (!Overflow || ICmpInst::isEquality(P: Pred)) {
4609 Value *NewCmp = Builder.CreateICmp(
4610 P: Pred, LHS: WO->getLHS(), RHS: ConstantInt::get(Ty: WO->getLHS()->getType(), V: NewC));
4611 return BinaryOperator::CreateOr(V1: Ov, V2: NewCmp);
4612 }
4613 }
4614
4615 // Try to fold the pattern "Overflow | icmp pred Res, C2" into a single
4616 // comparison instruction for umul.with.overflow.
4617 if (Value *R = foldOrUnsignedUMulOverflowICmp(I, Builder, DL))
4618 return replaceInstUsesWith(I, V: R);
4619
4620 // (~x) | y --> ~(x & (~y)) iff that gets rid of inversions
4621 if (sinkNotIntoOtherHandOfLogicalOp(I))
4622 return &I;
4623
4624 // Improve "get low bit mask up to and including bit X" pattern:
4625 // (1 << X) | ((1 << X) + -1) --> -1 l>> (bitwidth(x) - 1 - X)
4626 if (match(V: &I, P: m_c_Or(L: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: X)), R: m_AllOnes()),
4627 R: m_Shl(L: m_One(), R: m_Deferred(V: X)))) &&
4628 match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_Value()), R: m_Value()))) {
4629 Value *Sub = Builder.CreateSub(
4630 LHS: ConstantInt::get(Ty, V: Ty->getScalarSizeInBits() - 1), RHS: X);
4631 return BinaryOperator::CreateLShr(V1: Constant::getAllOnesValue(Ty), V2: Sub);
4632 }
4633
4634 // An or recurrence w/loop invariant step is equivelent to (or start, step)
4635 PHINode *PN = nullptr;
4636 Value *Start = nullptr, *Step = nullptr;
4637 if (matchSimpleRecurrence(I: &I, P&: PN, Start, Step) && DT.dominates(Def: Step, User: PN))
4638 return replaceInstUsesWith(I, V: Builder.CreateOr(LHS: Start, RHS: Step));
4639
4640 // (A & B) | (C | D) or (C | D) | (A & B)
4641 // Can be combined if C or D is of type (A/B & X)
4642 if (match(V: &I, P: m_c_Or(L: m_OneUse(SubPattern: m_And(L: m_Value(V&: A), R: m_Value(V&: B))),
4643 R: m_OneUse(SubPattern: m_Or(L: m_Value(V&: C), R: m_Value(V&: D)))))) {
4644 // (A & B) | (C | ?) -> C | (? | (A & B))
4645 // (A & B) | (C | ?) -> C | (? | (A & B))
4646 // (A & B) | (C | ?) -> C | (? | (A & B))
4647 // (A & B) | (C | ?) -> C | (? | (A & B))
4648 // (C | ?) | (A & B) -> C | (? | (A & B))
4649 // (C | ?) | (A & B) -> C | (? | (A & B))
4650 // (C | ?) | (A & B) -> C | (? | (A & B))
4651 // (C | ?) | (A & B) -> C | (? | (A & B))
4652 if (match(V: D, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: A), R: m_Value()))) ||
4653 match(V: D, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: B), R: m_Value()))))
4654 return BinaryOperator::CreateOr(
4655 V1: C, V2: Builder.CreateOr(LHS: D, RHS: Builder.CreateAnd(LHS: A, RHS: B)));
4656 // (A & B) | (? | D) -> (? | (A & B)) | D
4657 // (A & B) | (? | D) -> (? | (A & B)) | D
4658 // (A & B) | (? | D) -> (? | (A & B)) | D
4659 // (A & B) | (? | D) -> (? | (A & B)) | D
4660 // (? | D) | (A & B) -> (? | (A & B)) | D
4661 // (? | D) | (A & B) -> (? | (A & B)) | D
4662 // (? | D) | (A & B) -> (? | (A & B)) | D
4663 // (? | D) | (A & B) -> (? | (A & B)) | D
4664 if (match(V: C, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: A), R: m_Value()))) ||
4665 match(V: C, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: B), R: m_Value()))))
4666 return BinaryOperator::CreateOr(
4667 V1: Builder.CreateOr(LHS: C, RHS: Builder.CreateAnd(LHS: A, RHS: B)), V2: D);
4668 }
4669
4670 if (Instruction *R = reassociateForUses(BO&: I, Builder))
4671 return R;
4672
4673 if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
4674 return Canonicalized;
4675
4676 if (Instruction *Folded = foldLogicOfIsFPClass(BO&: I, Op0, Op1))
4677 return Folded;
4678
4679 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
4680 return Res;
4681
4682 // If we are setting the sign bit of a floating-point value, convert
4683 // this to fneg(fabs), then cast back to integer.
4684 //
4685 // If the result isn't immediately cast back to a float, this will increase
4686 // the number of instructions. This is still probably a better canonical form
4687 // as it enables FP value tracking.
4688 //
4689 // Assumes any IEEE-represented type has the sign bit in the high bit.
4690 //
4691 // This is generous interpretation of noimplicitfloat, this is not a true
4692 // floating-point operation.
4693 Value *CastOp;
4694 if (match(V: Op0, P: m_ElementWiseBitCast(Op: m_Value(V&: CastOp))) &&
4695 match(V: Op1, P: m_SignMask()) &&
4696 !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
4697 Kind: Attribute::NoImplicitFloat)) {
4698 Type *EltTy = CastOp->getType()->getScalarType();
4699 if (EltTy->isFloatingPointTy() &&
4700 APFloat::hasSignBitInMSB(EltTy->getFltSemantics())) {
4701 Value *FAbs = Builder.CreateFAbs(V: CastOp);
4702 Value *FNegFAbs = Builder.CreateFNeg(V: FAbs);
4703 return new BitCastInst(FNegFAbs, I.getType());
4704 }
4705 }
4706
4707 // (X & C1) | C2 -> X & (C1 | C2) iff (X & C2) == C2
4708 if (match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) &&
4709 match(V: Op1, P: m_APInt(Res&: C2))) {
4710 KnownBits KnownX = computeKnownBits(V: X, CxtI: &I);
4711 if ((KnownX.One & *C2) == *C2)
4712 return BinaryOperator::CreateAnd(V1: X, V2: ConstantInt::get(Ty, V: *C1 | *C2));
4713 }
4714
4715 if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
4716 return Res;
4717
4718 if (Value *V =
4719 simplifyAndOrWithOpReplaced(V: Op0, Op: Op1, RepOp: Constant::getNullValue(Ty),
4720 /*SimplifyOnly*/ false, IC&: *this))
4721 return BinaryOperator::CreateOr(V1: V, V2: Op1);
4722 if (Value *V =
4723 simplifyAndOrWithOpReplaced(V: Op1, Op: Op0, RepOp: Constant::getNullValue(Ty),
4724 /*SimplifyOnly*/ false, IC&: *this))
4725 return BinaryOperator::CreateOr(V1: Op0, V2: V);
4726
4727 if (cast<PossiblyDisjointInst>(Val&: I).isDisjoint())
4728 if (Value *V = SimplifyAddWithRemainder(I))
4729 return replaceInstUsesWith(I, V);
4730
4731 if (Value *Res = FoldOrOfSelectSmaxToAbs(I, Builder))
4732 return replaceInstUsesWith(I, V: Res);
4733
4734 // signum: or (ashr X, BW-1), zext (icmp ne|sgt X, 0) --> scmp(X, 0)
4735 // The ashr already supplies -1 for negative X, so any predicate that
4736 // produces 1 for positive X and 0 for X == 0 yields the same result here.
4737 {
4738 Value *X;
4739 CmpPredicate SignPred;
4740 unsigned BitWidth = Ty->getScalarSizeInBits();
4741 if (match(V: &I,
4742 P: m_c_Or(L: m_AShr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(V: BitWidth - 1)),
4743 R: m_ZExt(Op: m_ICmp(Pred&: SignPred, L: m_Deferred(V: X), R: m_ZeroInt())))) &&
4744 (SignPred == ICmpInst::ICMP_NE || SignPred == ICmpInst::ICMP_SGT) &&
4745 (Op0->hasOneUse() || Op1->hasOneUse()))
4746 return replaceInstUsesWith(
4747 I, V: Builder.CreateIntrinsic(RetTy: Ty, ID: Intrinsic::scmp,
4748 Args: {X, Constant::getNullValue(Ty)}));
4749 }
4750
4751 return nullptr;
4752}
4753
4754/// A ^ B can be specified using other logic ops in a variety of patterns. We
4755/// can fold these early and efficiently by morphing an existing instruction.
4756static Instruction *foldXorToXor(BinaryOperator &I,
4757 InstCombiner::BuilderTy &Builder) {
4758 assert(I.getOpcode() == Instruction::Xor);
4759 Value *Op0 = I.getOperand(i_nocapture: 0);
4760 Value *Op1 = I.getOperand(i_nocapture: 1);
4761 Value *A, *B;
4762
4763 // There are 4 commuted variants for each of the basic patterns.
4764
4765 // (A & B) ^ (A | B) -> A ^ B
4766 // (A & B) ^ (B | A) -> A ^ B
4767 // (A | B) ^ (A & B) -> A ^ B
4768 // (A | B) ^ (B & A) -> A ^ B
4769 if (match(V: &I, P: m_c_Xor(L: m_And(L: m_Value(V&: A), R: m_Value(V&: B)),
4770 R: m_c_Or(L: m_Deferred(V: A), R: m_Deferred(V: B)))))
4771 return BinaryOperator::CreateXor(V1: A, V2: B);
4772
4773 // (A | ~B) ^ (~A | B) -> A ^ B
4774 // (~B | A) ^ (~A | B) -> A ^ B
4775 // (~A | B) ^ (A | ~B) -> A ^ B
4776 // (B | ~A) ^ (A | ~B) -> A ^ B
4777 if (match(V: &I, P: m_Xor(L: m_c_Or(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B))),
4778 R: m_c_Or(L: m_Not(V: m_Deferred(V: A)), R: m_Deferred(V: B)))))
4779 return BinaryOperator::CreateXor(V1: A, V2: B);
4780
4781 // (A & ~B) ^ (~A & B) -> A ^ B
4782 // (~B & A) ^ (~A & B) -> A ^ B
4783 // (~A & B) ^ (A & ~B) -> A ^ B
4784 // (B & ~A) ^ (A & ~B) -> A ^ B
4785 if (match(V: &I, P: m_Xor(L: m_c_And(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B))),
4786 R: m_c_And(L: m_Not(V: m_Deferred(V: A)), R: m_Deferred(V: B)))))
4787 return BinaryOperator::CreateXor(V1: A, V2: B);
4788
4789 // For the remaining cases we need to get rid of one of the operands.
4790 if (!Op0->hasOneUse() && !Op1->hasOneUse())
4791 return nullptr;
4792
4793 // (A | B) ^ ~(A & B) -> ~(A ^ B)
4794 // (A | B) ^ ~(B & A) -> ~(A ^ B)
4795 // (A & B) ^ ~(A | B) -> ~(A ^ B)
4796 // (A & B) ^ ~(B | A) -> ~(A ^ B)
4797 // Complexity sorting ensures the not will be on the right side.
4798 if ((match(V: Op0, P: m_Or(L: m_Value(V&: A), R: m_Value(V&: B))) &&
4799 match(V: Op1, P: m_Not(V: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))) ||
4800 (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
4801 match(V: Op1, P: m_Not(V: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))))
4802 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
4803
4804 return nullptr;
4805}
4806
4807Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
4808 BinaryOperator &I) {
4809 assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
4810 I.getOperand(1) == RHS && "Should be 'xor' with these operands");
4811
4812 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
4813 Value *LHS0 = LHS->getOperand(i_nocapture: 0), *LHS1 = LHS->getOperand(i_nocapture: 1);
4814 Value *RHS0 = RHS->getOperand(i_nocapture: 0), *RHS1 = RHS->getOperand(i_nocapture: 1);
4815
4816 if (predicatesFoldable(P1: PredL, P2: PredR)) {
4817 if (LHS0 == RHS1 && LHS1 == RHS0) {
4818 std::swap(a&: LHS0, b&: LHS1);
4819 PredL = ICmpInst::getSwappedPredicate(pred: PredL);
4820 }
4821 if (LHS0 == RHS0 && LHS1 == RHS1) {
4822 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4823 unsigned Code = getICmpCode(Pred: PredL) ^ getICmpCode(Pred: PredR);
4824 bool IsSigned = LHS->isSigned() || RHS->isSigned();
4825 return getNewICmpValue(Code, Sign: IsSigned, LHS: LHS0, RHS: LHS1, Builder);
4826 }
4827 }
4828
4829 const APInt *LC, *RC;
4830 if (match(V: LHS1, P: m_APInt(Res&: LC)) && match(V: RHS1, P: m_APInt(Res&: RC)) &&
4831 LHS0->getType() == RHS0->getType() &&
4832 LHS0->getType()->isIntOrIntVectorTy()) {
4833 // Convert xor of signbit tests to signbit test of xor'd values:
4834 // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
4835 // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
4836 // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
4837 // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
4838 bool TrueIfSignedL, TrueIfSignedR;
4839 if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
4840 isSignBitCheck(Pred: PredL, RHS: *LC, TrueIfSigned&: TrueIfSignedL) &&
4841 isSignBitCheck(Pred: PredR, RHS: *RC, TrueIfSigned&: TrueIfSignedR)) {
4842 Value *XorLR = Builder.CreateXor(LHS: LHS0, RHS: RHS0);
4843 return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(Arg: XorLR) :
4844 Builder.CreateIsNotNeg(Arg: XorLR);
4845 }
4846
4847 // Fold (icmp pred1 X, C1) ^ (icmp pred2 X, C2)
4848 // into a single comparison using range-based reasoning.
4849 if (LHS0 == RHS0) {
4850 ConstantRange CR1 = ConstantRange::makeExactICmpRegion(Pred: PredL, Other: *LC);
4851 ConstantRange CR2 = ConstantRange::makeExactICmpRegion(Pred: PredR, Other: *RC);
4852 auto CRUnion = CR1.exactUnionWith(CR: CR2);
4853 auto CRIntersect = CR1.exactIntersectWith(CR: CR2);
4854 if (CRUnion && CRIntersect)
4855 if (auto CR = CRUnion->exactIntersectWith(CR: CRIntersect->inverse())) {
4856 if (CR->isFullSet())
4857 return ConstantInt::getTrue(Ty: I.getType());
4858 if (CR->isEmptySet())
4859 return ConstantInt::getFalse(Ty: I.getType());
4860
4861 CmpInst::Predicate NewPred;
4862 APInt NewC, Offset;
4863 CR->getEquivalentICmp(Pred&: NewPred, RHS&: NewC, Offset);
4864
4865 if ((Offset.isZero() && (LHS->hasOneUse() || RHS->hasOneUse())) ||
4866 (LHS->hasOneUse() && RHS->hasOneUse())) {
4867 Value *NewV = LHS0;
4868 Type *Ty = LHS0->getType();
4869 if (!Offset.isZero())
4870 NewV = Builder.CreateAdd(LHS: NewV, RHS: ConstantInt::get(Ty, V: Offset));
4871 return Builder.CreateICmp(P: NewPred, LHS: NewV,
4872 RHS: ConstantInt::get(Ty, V: NewC));
4873 }
4874 }
4875 }
4876
4877 // Fold (icmp eq/ne (X & Pow2), 0) ^ (icmp eq/ne (Y & Pow2), 0) into
4878 // (icmp eq/ne ((X ^ Y) & Pow2), 0)
4879 Value *X, *Y, *Pow2;
4880 if (ICmpInst::isEquality(P: PredL) && ICmpInst::isEquality(P: PredR) &&
4881 LC->isZero() && RC->isZero() && LHS->hasOneUse() && RHS->hasOneUse() &&
4882 match(V: LHS0, P: m_And(L: m_Value(V&: X), R: m_Value(V&: Pow2))) &&
4883 match(V: RHS0, P: m_And(L: m_Value(V&: Y), R: m_Specific(V: Pow2))) &&
4884 isKnownToBeAPowerOfTwo(V: Pow2, /*OrZero=*/true, CxtI: &I)) {
4885 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
4886 Value *And = Builder.CreateAnd(LHS: Xor, RHS: Pow2);
4887 return Builder.CreateICmp(P: PredL == PredR ? ICmpInst::ICMP_NE
4888 : ICmpInst::ICMP_EQ,
4889 LHS: And, RHS: ConstantInt::getNullValue(Ty: Xor->getType()));
4890 }
4891 }
4892
4893 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
4894 // into those logic ops. That is, try to turn this into an and-of-icmps
4895 // because we have many folds for that pattern.
4896 //
4897 // This is based on a truth table definition of xor:
4898 // X ^ Y --> (X | Y) & !(X & Y)
4899 if (Value *OrICmp = simplifyBinOp(Opcode: Instruction::Or, LHS, RHS, Q: SQ)) {
4900 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
4901 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
4902 if (Value *AndICmp = simplifyBinOp(Opcode: Instruction::And, LHS, RHS, Q: SQ)) {
4903 // TODO: Independently handle cases where the 'and' side is a constant.
4904 ICmpInst *X = nullptr, *Y = nullptr;
4905 if (OrICmp == LHS && AndICmp == RHS) {
4906 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS --> X & !Y
4907 X = LHS;
4908 Y = RHS;
4909 }
4910 if (OrICmp == RHS && AndICmp == LHS) {
4911 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS --> !Y & X
4912 X = RHS;
4913 Y = LHS;
4914 }
4915 if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(V: Y, IgnoredUser: &I))) {
4916 // Invert the predicate of 'Y', thus inverting its output.
4917 Y->setPredicate(Y->getInversePredicate());
4918 // So, are there other uses of Y?
4919 if (!Y->hasOneUse()) {
4920 // We need to adapt other uses of Y though. Get a value that matches
4921 // the original value of Y before inversion. While this increases
4922 // immediate instruction count, we have just ensured that all the
4923 // users are freely-invertible, so that 'not' *will* get folded away.
4924 BuilderTy::InsertPointGuard Guard(Builder);
4925 // Set insertion point to right after the Y.
4926 Builder.SetInsertPoint(TheBB: Y->getParent(), IP: ++(Y->getIterator()));
4927 Value *NotY = Builder.CreateNot(V: Y, Name: Y->getName() + ".not");
4928 // Replace all uses of Y (excluding the one in NotY!) with NotY.
4929 Worklist.pushUsersToWorkList(I&: *Y);
4930 Y->replaceUsesWithIf(New: NotY,
4931 ShouldReplace: [NotY](Use &U) { return U.getUser() != NotY; });
4932 }
4933 // All done.
4934 return Builder.CreateAnd(LHS, RHS);
4935 }
4936 }
4937 }
4938
4939 return nullptr;
4940}
4941
4942/// If we have a masked merge, in the canonical form of:
4943/// (assuming that A only has one use.)
4944/// | A | |B|
4945/// ((x ^ y) & M) ^ y
4946/// | D |
4947/// * If M is inverted:
4948/// | D |
4949/// ((x ^ y) & ~M) ^ y
4950/// We can canonicalize by swapping the final xor operand
4951/// to eliminate the 'not' of the mask.
4952/// ((x ^ y) & M) ^ x
4953/// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
4954/// because that shortens the dependency chain and improves analysis:
4955/// (x & M) | (y & ~M)
4956static Instruction *visitMaskedMerge(BinaryOperator &I,
4957 InstCombiner::BuilderTy &Builder) {
4958 Value *B, *X, *D;
4959 Value *M;
4960 if (!match(V: &I, P: m_c_Xor(L: m_Value(V&: B),
4961 R: m_OneUse(SubPattern: m_c_And(
4962 L: m_Value(V&: D, P: m_c_Xor(L: m_Deferred(V: B), R: m_Value(V&: X))),
4963 R: m_Value(V&: M))))))
4964 return nullptr;
4965
4966 Value *NotM;
4967 if (match(V: M, P: m_Not(V: m_Value(V&: NotM)))) {
4968 // De-invert the mask and swap the value in B part.
4969 Value *NewA = Builder.CreateAnd(LHS: D, RHS: NotM);
4970 return BinaryOperator::CreateXor(V1: NewA, V2: X);
4971 }
4972
4973 Constant *C;
4974 if (D->hasOneUse() && match(V: M, P: m_Constant(C))) {
4975 // Propagating undef is unsafe. Clamp undef elements to -1.
4976 Type *EltTy = C->getType()->getScalarType();
4977 C = Constant::replaceUndefsWith(C, Replacement: ConstantInt::getAllOnesValue(Ty: EltTy));
4978 // Unfold.
4979 Value *LHS = Builder.CreateAnd(LHS: X, RHS: C);
4980 Value *NotC = Builder.CreateNot(V: C);
4981 Value *RHS = Builder.CreateAnd(LHS: B, RHS: NotC);
4982 return BinaryOperator::CreateOr(V1: LHS, V2: RHS);
4983 }
4984
4985 return nullptr;
4986}
4987
4988static Instruction *foldNotXor(BinaryOperator &I,
4989 InstCombiner::BuilderTy &Builder) {
4990 Value *X, *Y;
4991 // FIXME: one-use check is not needed in general, but currently we are unable
4992 // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
4993 if (!match(V: &I, P: m_Not(V: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: X), R: m_Value(V&: Y))))))
4994 return nullptr;
4995
4996 auto hasCommonOperand = [](Value *A, Value *B, Value *C, Value *D) {
4997 return A == C || A == D || B == C || B == D;
4998 };
4999
5000 Value *A, *B, *C, *D;
5001 // Canonicalize ~((A & B) ^ (A | ?)) -> (A & B) | ~(A | ?)
5002 // 4 commuted variants
5003 if (match(V: X, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
5004 match(V: Y, P: m_Or(L: m_Value(V&: C), R: m_Value(V&: D))) && hasCommonOperand(A, B, C, D)) {
5005 Value *NotY = Builder.CreateNot(V: Y);
5006 return BinaryOperator::CreateOr(V1: X, V2: NotY);
5007 };
5008
5009 // Canonicalize ~((A | ?) ^ (A & B)) -> (A & B) | ~(A | ?)
5010 // 4 commuted variants
5011 if (match(V: Y, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
5012 match(V: X, P: m_Or(L: m_Value(V&: C), R: m_Value(V&: D))) && hasCommonOperand(A, B, C, D)) {
5013 Value *NotX = Builder.CreateNot(V: X);
5014 return BinaryOperator::CreateOr(V1: Y, V2: NotX);
5015 };
5016
5017 return nullptr;
5018}
5019
5020/// Canonicalize a shifty way to code absolute value to the more common pattern
5021/// that uses negation and select.
5022static Instruction *canonicalizeAbs(BinaryOperator &Xor,
5023 InstCombiner::BuilderTy &Builder) {
5024 assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
5025
5026 // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
5027 // We're relying on the fact that we only do this transform when the shift has
5028 // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
5029 // instructions).
5030 Value *Op0 = Xor.getOperand(i_nocapture: 0), *Op1 = Xor.getOperand(i_nocapture: 1);
5031 if (Op0->hasNUses(N: 2))
5032 std::swap(a&: Op0, b&: Op1);
5033
5034 Type *Ty = Xor.getType();
5035 Value *A;
5036 const APInt *ShAmt;
5037 if (match(V: Op1, P: m_AShr(L: m_Value(V&: A), R: m_APInt(Res&: ShAmt))) &&
5038 Op1->hasNUses(N: 2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
5039 match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: A), R: m_Specific(V: Op1))))) {
5040 // Op1 = ashr i32 A, 31 ; smear the sign bit
5041 // xor (add A, Op1), Op1 ; add -1 and flip bits if negative
5042 // --> (A < 0) ? -A : A
5043 Value *IsNeg = Builder.CreateIsNeg(Arg: A);
5044 // Copy the nsw flags from the add to the negate.
5045 auto *Add = cast<BinaryOperator>(Val: Op0);
5046 Value *NegA = Add->hasNoUnsignedWrap()
5047 ? Constant::getNullValue(Ty: A->getType())
5048 : Builder.CreateNeg(V: A, Name: "", HasNSW: Add->hasNoSignedWrap());
5049 return SelectInst::Create(C: IsNeg, S1: NegA, S2: A);
5050 }
5051 return nullptr;
5052}
5053
5054static bool canFreelyInvert(InstCombiner &IC, Value *Op,
5055 Instruction *IgnoredUser) {
5056 auto *I = dyn_cast<Instruction>(Val: Op);
5057 return I && I->getInsertionPointAfterDef() &&
5058 IC.isFreeToInvert(V: I, /*WillInvertAllUses=*/true) &&
5059 IC.canFreelyInvertAllUsersOf(V: I, IgnoredUser);
5060}
5061
5062static Value *freelyInvert(InstCombinerImpl &IC, Value *Op,
5063 Instruction *IgnoredUser) {
5064 auto *I = cast<Instruction>(Val: Op);
5065 auto InsertPt = I->getInsertionPointAfterDef();
5066 assert(InsertPt &&
5067 "freelyInvert requires an instruction with a valid insertion point");
5068 IC.Builder.SetInsertPoint(*InsertPt);
5069 Value *NotOp = IC.Builder.CreateNot(V: Op, Name: Op->getName() + ".not");
5070 Op->replaceUsesWithIf(New: NotOp,
5071 ShouldReplace: [NotOp](Use &U) { return U.getUser() != NotOp; });
5072 IC.freelyInvertAllUsersOf(V: NotOp, IgnoredUser);
5073 return NotOp;
5074}
5075
5076// Transform
5077// z = ~(x &/| y)
5078// into:
5079// z = ((~x) |/& (~y))
5080// iff both x and y are free to invert and all uses of z can be freely updated.
5081bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
5082 Value *Op0, *Op1;
5083 if (!match(V: &I, P: m_LogicalOp(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
5084 return false;
5085
5086 // If this logic op has not been simplified yet, just bail out and let that
5087 // happen first. Otherwise, the code below may wrongly invert.
5088 if (Op0 == Op1)
5089 return false;
5090
5091 // If one of the operands is a user of the other,
5092 // freelyInvert->freelyInvertAllUsersOf will change the operands of I, which
5093 // may cause miscompilation.
5094 if (match(V: Op0, P: m_Not(V: m_Specific(V: Op1))) || match(V: Op1, P: m_Not(V: m_Specific(V: Op0))))
5095 return false;
5096
5097 Instruction::BinaryOps NewOpc =
5098 match(V: &I, P: m_LogicalAnd()) ? Instruction::Or : Instruction::And;
5099 bool IsBinaryOp = isa<BinaryOperator>(Val: I);
5100
5101 // Can our users be adapted?
5102 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
5103 return false;
5104
5105 // And can the operands be adapted?
5106 if (!canFreelyInvert(IC&: *this, Op: Op0, IgnoredUser: &I) || !canFreelyInvert(IC&: *this, Op: Op1, IgnoredUser: &I))
5107 return false;
5108
5109 Op0 = freelyInvert(IC&: *this, Op: Op0, IgnoredUser: &I);
5110 Op1 = freelyInvert(IC&: *this, Op: Op1, IgnoredUser: &I);
5111
5112 auto InsertPt = I.getInsertionPointAfterDef();
5113 assert(InsertPt && "sinkNotIntoLogicalOp requires an instruction with a "
5114 "valid insertion point");
5115 Builder.SetInsertPoint(*InsertPt);
5116 Value *NewLogicOp;
5117 if (IsBinaryOp) {
5118 NewLogicOp = Builder.CreateBinOp(Opc: NewOpc, LHS: Op0, RHS: Op1, Name: I.getName() + ".not");
5119 } else {
5120 NewLogicOp =
5121 Builder.CreateLogicalOp(Opc: NewOpc, Cond1: Op0, Cond2: Op1, Name: I.getName() + ".not",
5122 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : &I);
5123 if (SelectInst *SI = dyn_cast<SelectInst>(Val: NewLogicOp))
5124 SI->swapProfMetadata();
5125 }
5126
5127 replaceInstUsesWith(I, V: NewLogicOp);
5128 // We can not just create an outer `not`, it will most likely be immediately
5129 // folded back, reconstructing our initial pattern, and causing an
5130 // infinite combine loop, so immediately manually fold it away.
5131 freelyInvertAllUsersOf(V: NewLogicOp);
5132 return true;
5133}
5134
5135// Transform
5136// z = (~x) &/| y
5137// into:
5138// z = ~(x |/& (~y))
5139// iff y is free to invert and all uses of z can be freely updated.
5140bool InstCombinerImpl::sinkNotIntoOtherHandOfLogicalOp(Instruction &I) {
5141 Value *Op0, *Op1;
5142 if (!match(V: &I, P: m_LogicalOp(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
5143 return false;
5144 Instruction::BinaryOps NewOpc =
5145 match(V: &I, P: m_LogicalAnd()) ? Instruction::Or : Instruction::And;
5146 bool IsBinaryOp = isa<BinaryOperator>(Val: I);
5147
5148 Value *NotOp0 = nullptr;
5149 Value *NotOp1 = nullptr;
5150 Value **OpToInvert = nullptr;
5151 if (match(V: Op0, P: m_Not(V: m_Value(V&: NotOp0))) && canFreelyInvert(IC&: *this, Op: Op1, IgnoredUser: &I)) {
5152 Op0 = NotOp0;
5153 OpToInvert = &Op1;
5154 } else if (match(V: Op1, P: m_Not(V: m_Value(V&: NotOp1))) &&
5155 canFreelyInvert(IC&: *this, Op: Op0, IgnoredUser: &I)) {
5156 Op1 = NotOp1;
5157 OpToInvert = &Op0;
5158 } else
5159 return false;
5160
5161 // And can our users be adapted?
5162 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
5163 return false;
5164
5165 *OpToInvert = freelyInvert(IC&: *this, Op: *OpToInvert, IgnoredUser: &I);
5166
5167 Builder.SetInsertPoint(*I.getInsertionPointAfterDef());
5168 Value *NewBinOp;
5169 if (IsBinaryOp)
5170 NewBinOp = Builder.CreateBinOp(Opc: NewOpc, LHS: Op0, RHS: Op1, Name: I.getName() + ".not");
5171 else
5172 NewBinOp = Builder.CreateLogicalOp(Opc: NewOpc, Cond1: Op0, Cond2: Op1, Name: I.getName() + ".not");
5173 replaceInstUsesWith(I, V: NewBinOp);
5174 // We can not just create an outer `not`, it will most likely be immediately
5175 // folded back, reconstructing our initial pattern, and causing an
5176 // infinite combine loop, so immediately manually fold it away.
5177 freelyInvertAllUsersOf(V: NewBinOp);
5178 return true;
5179}
5180
5181Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
5182 Value *NotOp;
5183 if (!match(V: &I, P: m_Not(V: m_Value(V&: NotOp))))
5184 return nullptr;
5185
5186 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
5187 // We must eliminate the and/or (one-use) for these transforms to not increase
5188 // the instruction count.
5189 //
5190 // ~(~X & Y) --> (X | ~Y)
5191 // ~(Y & ~X) --> (X | ~Y)
5192 //
5193 // Note: The logical matches do not check for the commuted patterns because
5194 // those are handled via SimplifySelectsFeedingBinaryOp().
5195 Type *Ty = I.getType();
5196 Value *X, *Y;
5197 if (match(V: NotOp, P: m_OneUse(SubPattern: m_c_And(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))) {
5198 Value *NotY = Builder.CreateNot(V: Y, Name: Y->getName() + ".not");
5199 return BinaryOperator::CreateOr(V1: X, V2: NotY);
5200 }
5201 if (match(V: NotOp, P: m_OneUse(SubPattern: m_LogicalAnd(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))) {
5202 Value *NotY = Builder.CreateNot(V: Y, Name: Y->getName() + ".not");
5203 SelectInst *SI = SelectInst::Create(
5204 C: X, S1: ConstantInt::getTrue(Ty), S2: NotY, NameStr: "", InsertBefore: nullptr,
5205 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: NotOp));
5206 SI->swapProfMetadata();
5207 return SI;
5208 }
5209
5210 // ~(~X | Y) --> (X & ~Y)
5211 // ~(Y | ~X) --> (X & ~Y)
5212 if (match(V: NotOp, P: m_OneUse(SubPattern: m_c_Or(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))) {
5213 Value *NotY = Builder.CreateNot(V: Y, Name: Y->getName() + ".not");
5214 return BinaryOperator::CreateAnd(V1: X, V2: NotY);
5215 }
5216 if (match(V: NotOp, P: m_OneUse(SubPattern: m_LogicalOr(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))) {
5217 Value *NotY = Builder.CreateNot(V: Y, Name: Y->getName() + ".not");
5218 SelectInst *SI = SelectInst::Create(
5219 C: X, S1: NotY, S2: ConstantInt::getFalse(Ty), NameStr: "", InsertBefore: nullptr,
5220 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: NotOp));
5221 SI->swapProfMetadata();
5222 return SI;
5223 }
5224
5225 // Is this a 'not' (~) fed by a binary operator?
5226 BinaryOperator *NotVal;
5227 if (match(V: NotOp, P: m_BinOp(I&: NotVal))) {
5228 // ~((-X) | Y) --> (X - 1) & (~Y)
5229 if (match(V: NotVal,
5230 P: m_OneUse(SubPattern: m_c_Or(L: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))), R: m_Value(V&: Y))))) {
5231 Value *DecX = Builder.CreateAdd(LHS: X, RHS: ConstantInt::getAllOnesValue(Ty));
5232 Value *NotY = Builder.CreateNot(V: Y);
5233 return BinaryOperator::CreateAnd(V1: DecX, V2: NotY);
5234 }
5235
5236 // ~(~X >>s Y) --> (X >>s Y)
5237 if (match(V: NotVal, P: m_AShr(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))
5238 return BinaryOperator::CreateAShr(V1: X, V2: Y);
5239
5240 // Treat lshr with non-negative operand as ashr.
5241 // ~(~X >>u Y) --> (X >>s Y) iff X is known negative
5242 if (match(V: NotVal, P: m_LShr(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))) &&
5243 isKnownNegative(V: X, SQ: SQ.getWithInstruction(I: NotVal)))
5244 return BinaryOperator::CreateAShr(V1: X, V2: Y);
5245
5246 // Bit-hack form of a signbit test for iN type:
5247 // ~(X >>s (N - 1)) --> sext i1 (X > -1) to iN
5248 unsigned FullShift = Ty->getScalarSizeInBits() - 1;
5249 if (match(V: NotVal, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: X), R: m_SpecificInt(V: FullShift))))) {
5250 Value *IsNotNeg = Builder.CreateIsNotNeg(Arg: X, Name: "isnotneg");
5251 return new SExtInst(IsNotNeg, Ty);
5252 }
5253
5254 // If we are inverting a right-shifted constant, we may be able to eliminate
5255 // the 'not' by inverting the constant and using the opposite shift type.
5256 // Canonicalization rules ensure that only a negative constant uses 'ashr',
5257 // but we must check that in case that transform has not fired yet.
5258
5259 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
5260 Constant *C;
5261 if (match(V: NotVal, P: m_AShr(L: m_Constant(C), R: m_Value(V&: Y))) &&
5262 match(V: C, P: m_Negative()))
5263 return BinaryOperator::CreateLShr(V1: ConstantExpr::getNot(C), V2: Y);
5264
5265 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
5266 if (match(V: NotVal, P: m_LShr(L: m_Constant(C), R: m_Value(V&: Y))) &&
5267 match(V: C, P: m_NonNegative()))
5268 return BinaryOperator::CreateAShr(V1: ConstantExpr::getNot(C), V2: Y);
5269
5270 // ~(X + C) --> ~C - X
5271 if (match(V: NotVal, P: m_Add(L: m_Value(V&: X), R: m_ImmConstant(C))))
5272 return BinaryOperator::CreateSub(V1: ConstantExpr::getNot(C), V2: X);
5273
5274 // ~(X - Y) --> ~X + Y
5275 // FIXME: is it really beneficial to sink the `not` here?
5276 if (match(V: NotVal, P: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y))))
5277 if (isa<Constant>(Val: X) || NotVal->hasOneUse())
5278 return BinaryOperator::CreateAdd(V1: Builder.CreateNot(V: X), V2: Y);
5279
5280 // ~(~X + Y) --> X - Y
5281 if (match(V: NotVal, P: m_c_Add(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y))))
5282 return BinaryOperator::CreateWithCopiedFlags(Opc: Instruction::Sub, V1: X, V2: Y,
5283 CopyO: NotVal);
5284 }
5285
5286 // not (cmp A, B) = !cmp A, B
5287 CmpPredicate Pred;
5288 if (match(V: NotOp, P: m_Cmp(Pred, L: m_Value(), R: m_Value())) &&
5289 (NotOp->hasOneUse() ||
5290 InstCombiner::canFreelyInvertAllUsersOf(V: cast<Instruction>(Val: NotOp),
5291 /*IgnoredUser=*/nullptr))) {
5292 cast<CmpInst>(Val: NotOp)->setPredicate(CmpInst::getInversePredicate(pred: Pred));
5293 freelyInvertAllUsersOf(V: NotOp);
5294 return &I;
5295 }
5296
5297 // not (bitcast (cmp A, B) --> bitcast (!cmp A, B)
5298 if (match(V: NotOp, P: m_OneUse(SubPattern: m_BitCast(Op: m_Value(V&: X)))) &&
5299 match(V: X, P: m_OneUse(SubPattern: m_Cmp(Pred, L: m_Value(), R: m_Value())))) {
5300 cast<CmpInst>(Val: X)->setPredicate(CmpInst::getInversePredicate(pred: Pred));
5301 return new BitCastInst(X, Ty);
5302 }
5303
5304 // Move a 'not' ahead of casts of a bool to enable logic reduction:
5305 // not (bitcast (sext i1 X)) --> bitcast (sext (not i1 X))
5306 if (match(V: NotOp, P: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X)))))) &&
5307 X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
5308 Type *SextTy = cast<BitCastOperator>(Val: NotOp)->getSrcTy();
5309 Value *NotX = Builder.CreateNot(V: X);
5310 Value *Sext = Builder.CreateSExt(V: NotX, DestTy: SextTy);
5311 return new BitCastInst(Sext, Ty);
5312 }
5313
5314 if (auto *NotOpI = dyn_cast<Instruction>(Val: NotOp))
5315 if (sinkNotIntoLogicalOp(I&: *NotOpI))
5316 return &I;
5317
5318 // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
5319 // ~min(~X, ~Y) --> max(X, Y)
5320 // ~max(~X, Y) --> min(X, ~Y)
5321 auto *II = dyn_cast<IntrinsicInst>(Val: NotOp);
5322 if (II && II->hasOneUse()) {
5323 if (match(V: NotOp, P: m_c_MaxOrMin(L: m_Not(V: m_Value(V&: X)), R: m_Value(V&: Y)))) {
5324 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: II->getIntrinsicID());
5325 Value *NotY = Builder.CreateNot(V: Y);
5326 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(ID: InvID, LHS: X, RHS: NotY);
5327 return replaceInstUsesWith(I, V: InvMaxMin);
5328 }
5329
5330 if (II->getIntrinsicID() == Intrinsic::is_fpclass) {
5331 ConstantInt *ClassMask = cast<ConstantInt>(Val: II->getArgOperand(i: 1));
5332 II->setArgOperand(
5333 i: 1, v: ConstantInt::get(Ty: ClassMask->getType(),
5334 V: ~ClassMask->getZExtValue() & fcAllFlags));
5335 return replaceInstUsesWith(I, V: II);
5336 }
5337 }
5338
5339 if (NotOp->hasOneUse()) {
5340 // Pull 'not' into operands of select if both operands are one-use compares
5341 // or one is one-use compare and the other one is a constant.
5342 // Inverting the predicates eliminates the 'not' operation.
5343 // Example:
5344 // not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
5345 // select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
5346 // not (select ?, (cmp TPred, ?, ?), true -->
5347 // select ?, (cmp InvTPred, ?, ?), false
5348 if (auto *Sel = dyn_cast<SelectInst>(Val: NotOp)) {
5349 Value *TV = Sel->getTrueValue();
5350 Value *FV = Sel->getFalseValue();
5351 auto *CmpT = dyn_cast<CmpInst>(Val: TV);
5352 auto *CmpF = dyn_cast<CmpInst>(Val: FV);
5353 bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(Val: TV);
5354 bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(Val: FV);
5355 if (InvertibleT && InvertibleF) {
5356 if (CmpT)
5357 CmpT->setPredicate(CmpT->getInversePredicate());
5358 else
5359 Sel->setTrueValue(ConstantExpr::getNot(C: cast<Constant>(Val: TV)));
5360 if (CmpF)
5361 CmpF->setPredicate(CmpF->getInversePredicate());
5362 else
5363 Sel->setFalseValue(ConstantExpr::getNot(C: cast<Constant>(Val: FV)));
5364 return replaceInstUsesWith(I, V: Sel);
5365 }
5366 }
5367 }
5368
5369 if (Instruction *NewXor = foldNotXor(I, Builder))
5370 return NewXor;
5371
5372 // TODO: Could handle multi-use better by checking if all uses of NotOp (other
5373 // than I) can be inverted.
5374 if (Value *R = getFreelyInverted(V: NotOp, WillInvertAllUses: NotOp->hasOneUse(), Builder: &Builder))
5375 return replaceInstUsesWith(I, V: R);
5376
5377 return nullptr;
5378}
5379
5380// ((X + C) & M) ^ M --> (~C − X) & M
5381static Instruction *foldMaskedAddXorPattern(BinaryOperator &I,
5382 InstCombiner::BuilderTy &Builder) {
5383 Value *X, *Mask;
5384 Constant *AddC;
5385 BinaryOperator *AddInst;
5386 if (match(V: &I,
5387 P: m_Xor(L: m_OneUse(SubPattern: m_And(L: m_OneUse(SubPattern: m_CombineAnd(
5388 Ps: m_BinOp(I&: AddInst),
5389 Ps: m_Add(L: m_Value(V&: X), R: m_ImmConstant(C&: AddC)))),
5390 R: m_Value(V&: Mask))),
5391 R: m_Deferred(V: Mask)))) {
5392 Value *NotC = Builder.CreateNot(V: AddC);
5393 Value *NewSub = Builder.CreateSub(LHS: NotC, RHS: X, Name: "", HasNUW: AddInst->hasNoUnsignedWrap(),
5394 HasNSW: AddInst->hasNoSignedWrap());
5395 return BinaryOperator::CreateAnd(V1: NewSub, V2: Mask);
5396 }
5397
5398 return nullptr;
5399}
5400
5401// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
5402// here. We should standardize that construct where it is needed or choose some
5403// other way to ensure that commutated variants of patterns are not missed.
5404Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
5405 if (Value *V = simplifyXorInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
5406 Q: SQ.getWithInstruction(I: &I)))
5407 return replaceInstUsesWith(I, V);
5408
5409 if (SimplifyAssociativeOrCommutative(I))
5410 return &I;
5411
5412 if (Instruction *X = foldVectorBinop(Inst&: I))
5413 return X;
5414
5415 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
5416 return Phi;
5417
5418 if (Instruction *NewXor = foldXorToXor(I, Builder))
5419 return NewXor;
5420
5421 // (A&B)^(A&C) -> A&(B^C) etc
5422 if (Value *V = foldUsingDistributiveLaws(I))
5423 return replaceInstUsesWith(I, V);
5424
5425 // See if we can simplify any instructions used by the instruction whose sole
5426 // purpose is to compute bits we don't care about.
5427 if (SimplifyDemandedInstructionBits(Inst&: I))
5428 return &I;
5429
5430 if (Instruction *R = foldNot(I))
5431 return R;
5432
5433 if (Instruction *R = foldBinOpShiftWithShift(I))
5434 return R;
5435
5436 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5437 Value *X, *Y, *M;
5438
5439 // (X | Y) ^ M -> (X ^ M) ^ Y
5440 // (X | Y) ^ M -> (Y ^ M) ^ X
5441 if (match(V: &I, P: m_c_Xor(L: m_OneUse(SubPattern: m_DisjointOr(L: m_Value(V&: X), R: m_Value(V&: Y))),
5442 R: m_Value(V&: M)))) {
5443 if (Value *XorAC = simplifyXorInst(LHS: X, RHS: M, Q: SQ.getWithInstruction(I: &I)))
5444 return BinaryOperator::CreateXor(V1: XorAC, V2: Y);
5445
5446 if (Value *XorBC = simplifyXorInst(LHS: Y, RHS: M, Q: SQ.getWithInstruction(I: &I)))
5447 return BinaryOperator::CreateXor(V1: XorBC, V2: X);
5448 }
5449
5450 // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
5451 // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
5452 // calls in there are unnecessary as SimplifyDemandedInstructionBits should
5453 // have already taken care of those cases.
5454 if (match(V: &I, P: m_c_Xor(L: m_c_And(L: m_Not(V: m_Value(V&: M)), R: m_Value()),
5455 R: m_c_And(L: m_Deferred(V: M), R: m_Value())))) {
5456 if (isGuaranteedNotToBeUndef(V: M))
5457 return BinaryOperator::CreateDisjointOr(V1: Op0, V2: Op1);
5458 else
5459 return BinaryOperator::CreateOr(V1: Op0, V2: Op1);
5460 }
5461
5462 if (Instruction *Xor = visitMaskedMerge(I, Builder))
5463 return Xor;
5464
5465 Constant *C1;
5466 if (match(V: Op1, P: m_Constant(C&: C1))) {
5467 Constant *C2;
5468
5469 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_ImmConstant(C&: C2)))) &&
5470 match(V: C1, P: m_ImmConstant())) {
5471 // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2)
5472 C2 = Constant::replaceUndefsWith(
5473 C: C2, Replacement: Constant::getAllOnesValue(Ty: C2->getType()->getScalarType()));
5474 Value *And = Builder.CreateAnd(
5475 LHS: X, RHS: Constant::mergeUndefsWith(C: ConstantExpr::getNot(C: C2), Other: C1));
5476 return BinaryOperator::CreateXor(
5477 V1: And, V2: Constant::mergeUndefsWith(C: ConstantExpr::getXor(C1, C2), Other: C1));
5478 }
5479
5480 // Use DeMorgan and reassociation to eliminate a 'not' op.
5481 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Not(V: m_Value(V&: X)), R: m_Constant(C&: C2))))) {
5482 // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
5483 Value *And = Builder.CreateAnd(LHS: X, RHS: ConstantExpr::getNot(C: C2));
5484 return BinaryOperator::CreateXor(V1: And, V2: ConstantExpr::getNot(C: C1));
5485 }
5486 if (match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Not(V: m_Value(V&: X)), R: m_Constant(C&: C2))))) {
5487 // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
5488 Value *Or = Builder.CreateOr(LHS: X, RHS: ConstantExpr::getNot(C: C2));
5489 return BinaryOperator::CreateXor(V1: Or, V2: ConstantExpr::getNot(C: C1));
5490 }
5491
5492 // Convert xor ([trunc] (ashr X, BW-1)), C =>
5493 // select(X >s -1, C, ~C)
5494 // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
5495 // constant depending on whether this input is less than 0.
5496 const APInt *CA;
5497 if (match(V: Op0, P: m_OneUse(SubPattern: m_TruncOrSelf(
5498 Op: m_AShr(L: m_Value(V&: X), R: m_APIntAllowPoison(Res&: CA))))) &&
5499 *CA == X->getType()->getScalarSizeInBits() - 1 &&
5500 !match(V: C1, P: m_AllOnes())) {
5501 assert(!C1->isNullValue() && "Unexpected xor with 0");
5502 Value *IsNotNeg = Builder.CreateIsNotNeg(Arg: X);
5503 return createSelectInstWithUnknownProfile(C: IsNotNeg, S1: Op1,
5504 S2: Builder.CreateNot(V: Op1));
5505 }
5506 }
5507
5508 Type *Ty = I.getType();
5509 {
5510 const APInt *RHSC;
5511 if (match(V: Op1, P: m_APInt(Res&: RHSC))) {
5512 Value *X;
5513 const APInt *C;
5514 // (C - X) ^ signmaskC --> (C + signmaskC) - X
5515 if (RHSC->isSignMask() && match(V: Op0, P: m_Sub(L: m_APInt(Res&: C), R: m_Value(V&: X))))
5516 return BinaryOperator::CreateSub(V1: ConstantInt::get(Ty, V: *C + *RHSC), V2: X);
5517
5518 // (X + C) ^ signmaskC --> X + (C + signmaskC)
5519 if (RHSC->isSignMask() && match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))))
5520 return BinaryOperator::CreateAdd(V1: X, V2: ConstantInt::get(Ty, V: *C + *RHSC));
5521
5522 // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
5523 if (match(V: Op0, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: C))) &&
5524 MaskedValueIsZero(V: X, Mask: *C, CxtI: &I))
5525 return BinaryOperator::CreateXor(V1: X, V2: ConstantInt::get(Ty, V: *C ^ *RHSC));
5526
5527 // When X is a power-of-two or zero and zero input is poison:
5528 // ctlz(i32 X) ^ 31 --> cttz(X)
5529 // cttz(i32 X) ^ 31 --> ctlz(X)
5530 auto *II = dyn_cast<IntrinsicInst>(Val: Op0);
5531 if (II && II->hasOneUse() && *RHSC == Ty->getScalarSizeInBits() - 1) {
5532 Intrinsic::ID IID = II->getIntrinsicID();
5533 if ((IID == Intrinsic::ctlz || IID == Intrinsic::cttz) &&
5534 match(V: II->getArgOperand(i: 1), P: m_One()) &&
5535 isKnownToBeAPowerOfTwo(V: II->getArgOperand(i: 0), /*OrZero */ true)) {
5536 IID = (IID == Intrinsic::ctlz) ? Intrinsic::cttz : Intrinsic::ctlz;
5537 Function *F =
5538 Intrinsic::getOrInsertDeclaration(M: II->getModule(), id: IID, OverloadTys: Ty);
5539 return CallInst::Create(Func: F, Args: {II->getArgOperand(i: 0), Builder.getTrue()});
5540 }
5541 }
5542
5543 // If RHSC is inverting the remaining bits of shifted X,
5544 // canonicalize to a 'not' before the shift to help SCEV and codegen:
5545 // (X << C) ^ RHSC --> ~X << C
5546 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C)))) &&
5547 *RHSC == APInt::getAllOnes(numBits: Ty->getScalarSizeInBits()).shl(ShiftAmt: *C)) {
5548 Value *NotX = Builder.CreateNot(V: X);
5549 return BinaryOperator::CreateShl(V1: NotX, V2: ConstantInt::get(Ty, V: *C));
5550 }
5551 // (X >>u C) ^ RHSC --> ~X >>u C
5552 if (match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: X), R: m_APInt(Res&: C)))) &&
5553 *RHSC == APInt::getAllOnes(numBits: Ty->getScalarSizeInBits()).lshr(ShiftAmt: *C)) {
5554 Value *NotX = Builder.CreateNot(V: X);
5555 return BinaryOperator::CreateLShr(V1: NotX, V2: ConstantInt::get(Ty, V: *C));
5556 }
5557 // TODO: We could handle 'ashr' here as well. That would be matching
5558 // a 'not' op and moving it before the shift. Doing that requires
5559 // preventing the inverse fold in canShiftBinOpWithConstantRHS().
5560 }
5561
5562 // If we are XORing the sign bit of a floating-point value, convert
5563 // this to fneg, then cast back to integer.
5564 //
5565 // This is generous interpretation of noimplicitfloat, this is not a true
5566 // floating-point operation.
5567 //
5568 // Assumes any IEEE-represented type has the sign bit in the high bit.
5569 // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
5570 Value *CastOp;
5571 if (match(V: Op0, P: m_ElementWiseBitCast(Op: m_Value(V&: CastOp))) &&
5572 match(V: Op1, P: m_SignMask()) &&
5573 !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
5574 Kind: Attribute::NoImplicitFloat)) {
5575 Type *EltTy = CastOp->getType()->getScalarType();
5576 if (EltTy->isFloatingPointTy() &&
5577 APFloat::hasSignBitInMSB(EltTy->getFltSemantics())) {
5578 Value *FNeg = Builder.CreateFNeg(V: CastOp);
5579 return new BitCastInst(FNeg, I.getType());
5580 }
5581 }
5582 }
5583
5584 // FIXME: This should not be limited to scalar (pull into APInt match above).
5585 {
5586 Value *X;
5587 ConstantInt *C1, *C2, *C3;
5588 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
5589 if (match(V: Op1, P: m_ConstantInt(CI&: C3)) &&
5590 match(V: Op0, P: m_LShr(L: m_Xor(L: m_Value(V&: X), R: m_ConstantInt(CI&: C1)),
5591 R: m_ConstantInt(CI&: C2))) &&
5592 Op0->hasOneUse()) {
5593 // fold (C1 >> C2) ^ C3
5594 APInt FoldConst = C1->getValue().lshr(ShiftAmt: C2->getValue());
5595 FoldConst ^= C3->getValue();
5596 // Prepare the two operands.
5597 auto *Opnd0 = Builder.CreateLShr(LHS: X, RHS: C2);
5598 Opnd0->takeName(V: Op0);
5599 return BinaryOperator::CreateXor(V1: Opnd0, V2: ConstantInt::get(Ty, V: FoldConst));
5600 }
5601 }
5602
5603 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
5604 return FoldedLogic;
5605
5606 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Op&: I))
5607 return FoldedLogic;
5608
5609 // Y ^ (X | Y) --> X & ~Y
5610 // Y ^ (Y | X) --> X & ~Y
5611 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Or(L: m_Value(V&: X), R: m_Specific(V: Op0)))))
5612 return BinaryOperator::CreateAnd(V1: X, V2: Builder.CreateNot(V: Op0));
5613 // (X | Y) ^ Y --> X & ~Y
5614 // (Y | X) ^ Y --> X & ~Y
5615 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
5616 return BinaryOperator::CreateAnd(V1: X, V2: Builder.CreateNot(V: Op1));
5617
5618 // Y ^ (X & Y) --> ~X & Y
5619 // Y ^ (Y & X) --> ~X & Y
5620 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: X), R: m_Specific(V: Op0)))))
5621 return BinaryOperator::CreateAnd(V1: Op0, V2: Builder.CreateNot(V: X));
5622 // (X & Y) ^ Y --> ~X & Y
5623 // (Y & X) ^ Y --> ~X & Y
5624 // Canonical form is (X & C) ^ C; don't touch that.
5625 // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
5626 // be fixed to prefer that (otherwise we get infinite looping).
5627 if (!match(V: Op1, P: m_Constant()) &&
5628 match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
5629 return BinaryOperator::CreateAnd(V1: Op1, V2: Builder.CreateNot(V: X));
5630
5631 Value *A, *B, *C;
5632 // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
5633 if (match(V: &I, P: m_c_Xor(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))),
5634 R: m_OneUse(SubPattern: m_c_Or(L: m_Deferred(V: A), R: m_Value(V&: C))))))
5635 return BinaryOperator::CreateXor(
5636 V1: Builder.CreateAnd(LHS: Builder.CreateNot(V: A), RHS: C), V2: B);
5637
5638 // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
5639 if (match(V: &I, P: m_c_Xor(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))),
5640 R: m_OneUse(SubPattern: m_c_Or(L: m_Deferred(V: B), R: m_Value(V&: C))))))
5641 return BinaryOperator::CreateXor(
5642 V1: Builder.CreateAnd(LHS: Builder.CreateNot(V: B), RHS: C), V2: A);
5643
5644 // (A & B) ^ (A ^ B) -> (A | B)
5645 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
5646 match(V: Op1, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
5647 return BinaryOperator::CreateOr(V1: A, V2: B);
5648 // (A ^ B) ^ (A & B) -> (A | B)
5649 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
5650 match(V: Op1, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
5651 return BinaryOperator::CreateOr(V1: A, V2: B);
5652
5653 // (A & ~B) ^ ~A -> ~(A & B)
5654 // (~B & A) ^ ~A -> ~(A & B)
5655 if (match(V: Op0, P: m_c_And(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B)))) &&
5656 match(V: Op1, P: m_Not(V: m_Specific(V: A))))
5657 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: A, RHS: B));
5658
5659 // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
5660 if (match(V: &I, P: m_c_Xor(L: m_c_And(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B)), R: m_Deferred(V: A))))
5661 return BinaryOperator::CreateOr(V1: A, V2: B);
5662
5663 // (~A | B) ^ A --> ~(A & B)
5664 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Not(V: m_Specific(V: Op1)), R: m_Value(V&: B)))))
5665 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: Op1, RHS: B));
5666
5667 // A ^ (~A | B) --> ~(A & B)
5668 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Or(L: m_Not(V: m_Specific(V: Op0)), R: m_Value(V&: B)))))
5669 return BinaryOperator::CreateNot(Op: Builder.CreateAnd(LHS: Op0, RHS: B));
5670
5671 // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
5672 // TODO: Loosen one-use restriction if common operand is a constant.
5673 Value *D;
5674 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: A), R: m_Value(V&: B)))) &&
5675 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: C), R: m_Value(V&: D))))) {
5676 if (B == C || B == D)
5677 std::swap(a&: A, b&: B);
5678 if (A == C)
5679 std::swap(a&: C, b&: D);
5680 if (A == D) {
5681 Value *NotA = Builder.CreateNot(V: A);
5682 return BinaryOperator::CreateAnd(V1: Builder.CreateXor(LHS: B, RHS: C), V2: NotA);
5683 }
5684 }
5685
5686 // (A & B) ^ (A | C) --> A ? ~B : C -- There are 4 commuted variants.
5687 if (I.getType()->isIntOrIntVectorTy(BitWidth: 1) &&
5688 match(V: &I, P: m_c_Xor(L: m_OneUse(SubPattern: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))),
5689 R: m_OneUse(SubPattern: m_LogicalOr(L: m_Value(V&: C), R: m_Value(V&: D)))))) {
5690 bool NeedFreeze = isa<SelectInst>(Val: Op0) && isa<SelectInst>(Val: Op1) && B == D;
5691 Instruction *MDFrom = cast<Instruction>(Val: Op0);
5692 if (B == C || B == D) {
5693 std::swap(a&: A, b&: B);
5694 MDFrom = B == C ? cast<Instruction>(Val: Op1) : nullptr;
5695 }
5696 if (A == C)
5697 std::swap(a&: C, b&: D);
5698 if (A == D) {
5699 if (NeedFreeze)
5700 A = Builder.CreateFreeze(V: A);
5701 Value *NotB = Builder.CreateNot(V: B);
5702 return MDFrom == nullptr || ProfcheckDisableMetadataFixes
5703 ? createSelectInstWithUnknownProfile(C: A, S1: NotB, S2: C)
5704 : SelectInst::Create(C: A, S1: NotB, S2: C, NameStr: "", InsertBefore: nullptr, MDFrom);
5705 }
5706 }
5707
5708 if (auto *LHS = dyn_cast<ICmpInst>(Val: I.getOperand(i_nocapture: 0)))
5709 if (auto *RHS = dyn_cast<ICmpInst>(Val: I.getOperand(i_nocapture: 1)))
5710 if (Value *V = foldXorOfICmps(LHS, RHS, I))
5711 return replaceInstUsesWith(I, V);
5712
5713 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
5714 return CastedXor;
5715
5716 if (Instruction *Abs = canonicalizeAbs(Xor&: I, Builder))
5717 return Abs;
5718
5719 // Otherwise, if all else failed, try to hoist the xor-by-constant:
5720 // (X ^ C) ^ Y --> (X ^ Y) ^ C
5721 // Just like we do in other places, we completely avoid the fold
5722 // for constantexprs, at least to avoid endless combine loop.
5723 if (match(V: &I, P: m_c_Xor(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: X, P: m_Unless(P: m_ConstantExpr())),
5724 R: m_ImmConstant(C&: C1))),
5725 R: m_Value(V&: Y))))
5726 return BinaryOperator::CreateXor(V1: Builder.CreateXor(LHS: X, RHS: Y), V2: C1);
5727
5728 if (Instruction *R = reassociateForUses(BO&: I, Builder))
5729 return R;
5730
5731 if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
5732 return Canonicalized;
5733
5734 if (Instruction *Folded = foldLogicOfIsFPClass(BO&: I, Op0, Op1))
5735 return Folded;
5736
5737 if (Instruction *Folded = canonicalizeConditionalNegationViaMathToSelect(I))
5738 return Folded;
5739
5740 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
5741 return Res;
5742
5743 if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
5744 return Res;
5745
5746 if (Instruction *Res = foldMaskedAddXorPattern(I, Builder))
5747 return Res;
5748
5749 return nullptr;
5750}
5751