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