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