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