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