1 //===- InstCombineSimplifyDemanded.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 contains logic for simplifying instructions based on information 10 // about how they are used. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/IR/IntrinsicInst.h" 17 #include "llvm/IR/PatternMatch.h" 18 #include "llvm/Support/KnownBits.h" 19 20 using namespace llvm; 21 using namespace llvm::PatternMatch; 22 23 #define DEBUG_TYPE "instcombine" 24 25 namespace { 26 27 struct AMDGPUImageDMaskIntrinsic { 28 unsigned Intr; 29 }; 30 31 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL 32 #include "InstCombineTables.inc" 33 34 } // end anonymous namespace 35 36 /// Check to see if the specified operand of the specified instruction is a 37 /// constant integer. If so, check to see if there are any bits set in the 38 /// constant that are not demanded. If so, shrink the constant and return true. 39 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 40 const APInt &Demanded) { 41 assert(I && "No instruction?"); 42 assert(OpNo < I->getNumOperands() && "Operand index too large"); 43 44 // The operand must be a constant integer or splat integer. 45 Value *Op = I->getOperand(OpNo); 46 const APInt *C; 47 if (!match(Op, m_APInt(C))) 48 return false; 49 50 // If there are no bits set that aren't demanded, nothing to do. 51 if (C->isSubsetOf(Demanded)) 52 return false; 53 54 // This instruction is producing bits that are not demanded. Shrink the RHS. 55 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded)); 56 57 return true; 58 } 59 60 61 62 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if 63 /// the instruction has any properties that allow us to simplify its operands. 64 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) { 65 unsigned BitWidth = Inst.getType()->getScalarSizeInBits(); 66 KnownBits Known(BitWidth); 67 APInt DemandedMask(APInt::getAllOnesValue(BitWidth)); 68 69 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known, 70 0, &Inst); 71 if (!V) return false; 72 if (V == &Inst) return true; 73 replaceInstUsesWith(Inst, V); 74 return true; 75 } 76 77 /// This form of SimplifyDemandedBits simplifies the specified instruction 78 /// operand if possible, updating it in place. It returns true if it made any 79 /// change and false otherwise. 80 bool InstCombiner::SimplifyDemandedBits(Instruction *I, unsigned OpNo, 81 const APInt &DemandedMask, 82 KnownBits &Known, 83 unsigned Depth) { 84 Use &U = I->getOperandUse(OpNo); 85 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known, 86 Depth, I); 87 if (!NewVal) return false; 88 U = NewVal; 89 return true; 90 } 91 92 93 /// This function attempts to replace V with a simpler value based on the 94 /// demanded bits. When this function is called, it is known that only the bits 95 /// set in DemandedMask of the result of V are ever used downstream. 96 /// Consequently, depending on the mask and V, it may be possible to replace V 97 /// with a constant or one of its operands. In such cases, this function does 98 /// the replacement and returns true. In all other cases, it returns false after 99 /// analyzing the expression and setting KnownOne and known to be one in the 100 /// expression. Known.Zero contains all the bits that are known to be zero in 101 /// the expression. These are provided to potentially allow the caller (which 102 /// might recursively be SimplifyDemandedBits itself) to simplify the 103 /// expression. 104 /// Known.One and Known.Zero always follow the invariant that: 105 /// Known.One & Known.Zero == 0. 106 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and 107 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note 108 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all 109 /// be the same. 110 /// 111 /// This returns null if it did not change anything and it permits no 112 /// simplification. This returns V itself if it did some simplification of V's 113 /// operands based on the information about what bits are demanded. This returns 114 /// some other non-null value if it found out that V is equal to another value 115 /// in the context where the specified bits are demanded, but not for all users. 116 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 117 KnownBits &Known, unsigned Depth, 118 Instruction *CxtI) { 119 assert(V != nullptr && "Null pointer of Value???"); 120 assert(Depth <= 6 && "Limit Search Depth"); 121 uint32_t BitWidth = DemandedMask.getBitWidth(); 122 Type *VTy = V->getType(); 123 assert( 124 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) && 125 Known.getBitWidth() == BitWidth && 126 "Value *V, DemandedMask and Known must have same BitWidth"); 127 128 if (isa<Constant>(V)) { 129 computeKnownBits(V, Known, Depth, CxtI); 130 return nullptr; 131 } 132 133 Known.resetAll(); 134 if (DemandedMask.isNullValue()) // Not demanding any bits from V. 135 return UndefValue::get(VTy); 136 137 if (Depth == 6) // Limit search depth. 138 return nullptr; 139 140 Instruction *I = dyn_cast<Instruction>(V); 141 if (!I) { 142 computeKnownBits(V, Known, Depth, CxtI); 143 return nullptr; // Only analyze instructions. 144 } 145 146 // If there are multiple uses of this value and we aren't at the root, then 147 // we can't do any simplifications of the operands, because DemandedMask 148 // only reflects the bits demanded by *one* of the users. 149 if (Depth != 0 && !I->hasOneUse()) 150 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI); 151 152 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth); 153 154 // If this is the root being simplified, allow it to have multiple uses, 155 // just set the DemandedMask to all bits so that we can try to simplify the 156 // operands. This allows visitTruncInst (for example) to simplify the 157 // operand of a trunc without duplicating all the logic below. 158 if (Depth == 0 && !V->hasOneUse()) 159 DemandedMask.setAllBits(); 160 161 switch (I->getOpcode()) { 162 default: 163 computeKnownBits(I, Known, Depth, CxtI); 164 break; 165 case Instruction::And: { 166 // If either the LHS or the RHS are Zero, the result is zero. 167 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 168 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, 169 Depth + 1)) 170 return I; 171 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 172 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 173 174 // Output known-0 are known to be clear if zero in either the LHS | RHS. 175 APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero; 176 // Output known-1 bits are only known if set in both the LHS & RHS. 177 APInt IKnownOne = RHSKnown.One & LHSKnown.One; 178 179 // If the client is only demanding bits that we know, return the known 180 // constant. 181 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 182 return Constant::getIntegerValue(VTy, IKnownOne); 183 184 // If all of the demanded bits are known 1 on one side, return the other. 185 // These bits cannot contribute to the result of the 'and'. 186 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 187 return I->getOperand(0); 188 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 189 return I->getOperand(1); 190 191 // If the RHS is a constant, see if we can simplify it. 192 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero)) 193 return I; 194 195 Known.Zero = std::move(IKnownZero); 196 Known.One = std::move(IKnownOne); 197 break; 198 } 199 case Instruction::Or: { 200 // If either the LHS or the RHS are One, the result is One. 201 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 202 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, 203 Depth + 1)) 204 return I; 205 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 206 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 207 208 // Output known-0 bits are only known if clear in both the LHS & RHS. 209 APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero; 210 // Output known-1 are known. to be set if s.et in either the LHS | RHS. 211 APInt IKnownOne = RHSKnown.One | LHSKnown.One; 212 213 // If the client is only demanding bits that we know, return the known 214 // constant. 215 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 216 return Constant::getIntegerValue(VTy, IKnownOne); 217 218 // If all of the demanded bits are known zero on one side, return the other. 219 // These bits cannot contribute to the result of the 'or'. 220 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 221 return I->getOperand(0); 222 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 223 return I->getOperand(1); 224 225 // If the RHS is a constant, see if we can simplify it. 226 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 227 return I; 228 229 Known.Zero = std::move(IKnownZero); 230 Known.One = std::move(IKnownOne); 231 break; 232 } 233 case Instruction::Xor: { 234 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 235 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1)) 236 return I; 237 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 238 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 239 240 // Output known-0 bits are known if clear or set in both the LHS & RHS. 241 APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) | 242 (RHSKnown.One & LHSKnown.One); 243 // Output known-1 are known to be set if set in only one of the LHS, RHS. 244 APInt IKnownOne = (RHSKnown.Zero & LHSKnown.One) | 245 (RHSKnown.One & LHSKnown.Zero); 246 247 // If the client is only demanding bits that we know, return the known 248 // constant. 249 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 250 return Constant::getIntegerValue(VTy, IKnownOne); 251 252 // If all of the demanded bits are known zero on one side, return the other. 253 // These bits cannot contribute to the result of the 'xor'. 254 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 255 return I->getOperand(0); 256 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 257 return I->getOperand(1); 258 259 // If all of the demanded bits are known to be zero on one side or the 260 // other, turn this into an *inclusive* or. 261 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 262 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) { 263 Instruction *Or = 264 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1), 265 I->getName()); 266 return InsertNewInstWith(Or, *I); 267 } 268 269 // If all of the demanded bits on one side are known, and all of the set 270 // bits on that side are also known to be set on the other side, turn this 271 // into an AND, as we know the bits will be cleared. 272 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 273 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) && 274 RHSKnown.One.isSubsetOf(LHSKnown.One)) { 275 Constant *AndC = Constant::getIntegerValue(VTy, 276 ~RHSKnown.One & DemandedMask); 277 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 278 return InsertNewInstWith(And, *I); 279 } 280 281 // If the RHS is a constant, see if we can simplify it. 282 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1. 283 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 284 return I; 285 286 // If our LHS is an 'and' and if it has one use, and if any of the bits we 287 // are flipping are known to be set, then the xor is just resetting those 288 // bits to zero. We can just knock out bits from the 'and' and the 'xor', 289 // simplifying both of them. 290 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) 291 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() && 292 isa<ConstantInt>(I->getOperand(1)) && 293 isa<ConstantInt>(LHSInst->getOperand(1)) && 294 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) { 295 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1)); 296 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1)); 297 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask); 298 299 Constant *AndC = 300 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue()); 301 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 302 InsertNewInstWith(NewAnd, *I); 303 304 Constant *XorC = 305 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue()); 306 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC); 307 return InsertNewInstWith(NewXor, *I); 308 } 309 310 // Output known-0 bits are known if clear or set in both the LHS & RHS. 311 Known.Zero = std::move(IKnownZero); 312 // Output known-1 are known to be set if set in only one of the LHS, RHS. 313 Known.One = std::move(IKnownOne); 314 break; 315 } 316 case Instruction::Select: { 317 Value *LHS, *RHS; 318 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor; 319 if (SPF == SPF_UMAX) { 320 // UMax(A, C) == A if ... 321 // The lowest non-zero bit of DemandMask is higher than the highest 322 // non-zero bit of C. 323 const APInt *C; 324 unsigned CTZ = DemandedMask.countTrailingZeros(); 325 if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits()) 326 return LHS; 327 } else if (SPF == SPF_UMIN) { 328 // UMin(A, C) == A if ... 329 // The lowest non-zero bit of DemandMask is higher than the highest 330 // non-one bit of C. 331 // This comes from using DeMorgans on the above umax example. 332 const APInt *C; 333 unsigned CTZ = DemandedMask.countTrailingZeros(); 334 if (match(RHS, m_APInt(C)) && 335 CTZ >= C->getBitWidth() - C->countLeadingOnes()) 336 return LHS; 337 } 338 339 // If this is a select as part of any other min/max pattern, don't simplify 340 // any further in case we break the structure. 341 if (SPF != SPF_UNKNOWN) 342 return nullptr; 343 344 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) || 345 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1)) 346 return I; 347 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 348 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 349 350 // If the operands are constants, see if we can simplify them. 351 if (ShrinkDemandedConstant(I, 1, DemandedMask) || 352 ShrinkDemandedConstant(I, 2, DemandedMask)) 353 return I; 354 355 // Only known if known in both the LHS and RHS. 356 Known.One = RHSKnown.One & LHSKnown.One; 357 Known.Zero = RHSKnown.Zero & LHSKnown.Zero; 358 break; 359 } 360 case Instruction::ZExt: 361 case Instruction::Trunc: { 362 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 363 364 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth); 365 KnownBits InputKnown(SrcBitWidth); 366 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1)) 367 return I; 368 Known = InputKnown.zextOrTrunc(BitWidth); 369 // Any top bits are known to be zero. 370 if (BitWidth > SrcBitWidth) 371 Known.Zero.setBitsFrom(SrcBitWidth); 372 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 373 break; 374 } 375 case Instruction::BitCast: 376 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy()) 377 return nullptr; // vector->int or fp->int? 378 379 if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) { 380 if (VectorType *SrcVTy = 381 dyn_cast<VectorType>(I->getOperand(0)->getType())) { 382 if (DstVTy->getNumElements() != SrcVTy->getNumElements()) 383 // Don't touch a bitcast between vectors of different element counts. 384 return nullptr; 385 } else 386 // Don't touch a scalar-to-vector bitcast. 387 return nullptr; 388 } else if (I->getOperand(0)->getType()->isVectorTy()) 389 // Don't touch a vector-to-scalar bitcast. 390 return nullptr; 391 392 if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1)) 393 return I; 394 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 395 break; 396 case Instruction::SExt: { 397 // Compute the bits in the result that are not present in the input. 398 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 399 400 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth); 401 402 // If any of the sign extended bits are demanded, we know that the sign 403 // bit is demanded. 404 if (DemandedMask.getActiveBits() > SrcBitWidth) 405 InputDemandedBits.setBit(SrcBitWidth-1); 406 407 KnownBits InputKnown(SrcBitWidth); 408 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1)) 409 return I; 410 411 // If the input sign bit is known zero, or if the NewBits are not demanded 412 // convert this into a zero extension. 413 if (InputKnown.isNonNegative() || 414 DemandedMask.getActiveBits() <= SrcBitWidth) { 415 // Convert to ZExt cast. 416 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName()); 417 return InsertNewInstWith(NewCast, *I); 418 } 419 420 // If the sign bit of the input is known set or clear, then we know the 421 // top bits of the result. 422 Known = InputKnown.sext(BitWidth); 423 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 424 break; 425 } 426 case Instruction::Add: 427 case Instruction::Sub: { 428 /// If the high-bits of an ADD/SUB are not demanded, then we do not care 429 /// about the high bits of the operands. 430 unsigned NLZ = DemandedMask.countLeadingZeros(); 431 // Right fill the mask of bits for this ADD/SUB to demand the most 432 // significant bit and all those below it. 433 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ)); 434 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) || 435 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) || 436 ShrinkDemandedConstant(I, 1, DemandedFromOps) || 437 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) { 438 if (NLZ > 0) { 439 // Disable the nsw and nuw flags here: We can no longer guarantee that 440 // we won't wrap after simplification. Removing the nsw/nuw flags is 441 // legal here because the top bit is not demanded. 442 BinaryOperator &BinOP = *cast<BinaryOperator>(I); 443 BinOP.setHasNoSignedWrap(false); 444 BinOP.setHasNoUnsignedWrap(false); 445 } 446 return I; 447 } 448 449 // If we are known to be adding/subtracting zeros to every bit below 450 // the highest demanded bit, we just return the other side. 451 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero)) 452 return I->getOperand(0); 453 // We can't do this with the LHS for subtraction, unless we are only 454 // demanding the LSB. 455 if ((I->getOpcode() == Instruction::Add || 456 DemandedFromOps.isOneValue()) && 457 DemandedFromOps.isSubsetOf(LHSKnown.Zero)) 458 return I->getOperand(1); 459 460 // Otherwise just compute the known bits of the result. 461 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 462 Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add, 463 NSW, LHSKnown, RHSKnown); 464 break; 465 } 466 case Instruction::Shl: { 467 const APInt *SA; 468 if (match(I->getOperand(1), m_APInt(SA))) { 469 const APInt *ShrAmt; 470 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt)))) 471 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0))) 472 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA, 473 DemandedMask, Known)) 474 return R; 475 476 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 477 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt)); 478 479 // If the shift is NUW/NSW, then it does demand the high bits. 480 ShlOperator *IOp = cast<ShlOperator>(I); 481 if (IOp->hasNoSignedWrap()) 482 DemandedMaskIn.setHighBits(ShiftAmt+1); 483 else if (IOp->hasNoUnsignedWrap()) 484 DemandedMaskIn.setHighBits(ShiftAmt); 485 486 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 487 return I; 488 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 489 Known.Zero <<= ShiftAmt; 490 Known.One <<= ShiftAmt; 491 // low bits known zero. 492 if (ShiftAmt) 493 Known.Zero.setLowBits(ShiftAmt); 494 } 495 break; 496 } 497 case Instruction::LShr: { 498 const APInt *SA; 499 if (match(I->getOperand(1), m_APInt(SA))) { 500 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 501 502 // Unsigned shift right. 503 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 504 505 // If the shift is exact, then it does demand the low bits (and knows that 506 // they are zero). 507 if (cast<LShrOperator>(I)->isExact()) 508 DemandedMaskIn.setLowBits(ShiftAmt); 509 510 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 511 return I; 512 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 513 Known.Zero.lshrInPlace(ShiftAmt); 514 Known.One.lshrInPlace(ShiftAmt); 515 if (ShiftAmt) 516 Known.Zero.setHighBits(ShiftAmt); // high bits known zero. 517 } 518 break; 519 } 520 case Instruction::AShr: { 521 // If this is an arithmetic shift right and only the low-bit is set, we can 522 // always convert this into a logical shr, even if the shift amount is 523 // variable. The low bit of the shift cannot be an input sign bit unless 524 // the shift amount is >= the size of the datatype, which is undefined. 525 if (DemandedMask.isOneValue()) { 526 // Perform the logical shift right. 527 Instruction *NewVal = BinaryOperator::CreateLShr( 528 I->getOperand(0), I->getOperand(1), I->getName()); 529 return InsertNewInstWith(NewVal, *I); 530 } 531 532 // If the sign bit is the only bit demanded by this ashr, then there is no 533 // need to do it, the shift doesn't change the high bit. 534 if (DemandedMask.isSignMask()) 535 return I->getOperand(0); 536 537 const APInt *SA; 538 if (match(I->getOperand(1), m_APInt(SA))) { 539 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 540 541 // Signed shift right. 542 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 543 // If any of the high bits are demanded, we should set the sign bit as 544 // demanded. 545 if (DemandedMask.countLeadingZeros() <= ShiftAmt) 546 DemandedMaskIn.setSignBit(); 547 548 // If the shift is exact, then it does demand the low bits (and knows that 549 // they are zero). 550 if (cast<AShrOperator>(I)->isExact()) 551 DemandedMaskIn.setLowBits(ShiftAmt); 552 553 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 554 return I; 555 556 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI); 557 558 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 559 // Compute the new bits that are at the top now plus sign bits. 560 APInt HighBits(APInt::getHighBitsSet( 561 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth))); 562 Known.Zero.lshrInPlace(ShiftAmt); 563 Known.One.lshrInPlace(ShiftAmt); 564 565 // If the input sign bit is known to be zero, or if none of the top bits 566 // are demanded, turn this into an unsigned shift right. 567 assert(BitWidth > ShiftAmt && "Shift amount not saturated?"); 568 if (Known.Zero[BitWidth-ShiftAmt-1] || 569 !DemandedMask.intersects(HighBits)) { 570 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0), 571 I->getOperand(1)); 572 LShr->setIsExact(cast<BinaryOperator>(I)->isExact()); 573 return InsertNewInstWith(LShr, *I); 574 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one. 575 Known.One |= HighBits; 576 } 577 } 578 break; 579 } 580 case Instruction::UDiv: { 581 // UDiv doesn't demand low bits that are zero in the divisor. 582 const APInt *SA; 583 if (match(I->getOperand(1), m_APInt(SA))) { 584 // If the shift is exact, then it does demand the low bits. 585 if (cast<UDivOperator>(I)->isExact()) 586 break; 587 588 // FIXME: Take the demanded mask of the result into account. 589 unsigned RHSTrailingZeros = SA->countTrailingZeros(); 590 APInt DemandedMaskIn = 591 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros); 592 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) 593 return I; 594 595 // Propagate zero bits from the input. 596 Known.Zero.setHighBits(std::min( 597 BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros)); 598 } 599 break; 600 } 601 case Instruction::SRem: 602 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 603 // X % -1 demands all the bits because we don't want to introduce 604 // INT_MIN % -1 (== undef) by accident. 605 if (Rem->isMinusOne()) 606 break; 607 APInt RA = Rem->getValue().abs(); 608 if (RA.isPowerOf2()) { 609 if (DemandedMask.ult(RA)) // srem won't affect demanded bits 610 return I->getOperand(0); 611 612 APInt LowBits = RA - 1; 613 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth); 614 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1)) 615 return I; 616 617 // The low bits of LHS are unchanged by the srem. 618 Known.Zero = LHSKnown.Zero & LowBits; 619 Known.One = LHSKnown.One & LowBits; 620 621 // If LHS is non-negative or has all low bits zero, then the upper bits 622 // are all zero. 623 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero)) 624 Known.Zero |= ~LowBits; 625 626 // If LHS is negative and not all low bits are zero, then the upper bits 627 // are all one. 628 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One)) 629 Known.One |= ~LowBits; 630 631 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 632 break; 633 } 634 } 635 636 // The sign bit is the LHS's sign bit, except when the result of the 637 // remainder is zero. 638 if (DemandedMask.isSignBitSet()) { 639 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI); 640 // If it's known zero, our sign bit is also zero. 641 if (LHSKnown.isNonNegative()) 642 Known.makeNonNegative(); 643 } 644 break; 645 case Instruction::URem: { 646 KnownBits Known2(BitWidth); 647 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 648 if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) || 649 SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1)) 650 return I; 651 652 unsigned Leaders = Known2.countMinLeadingZeros(); 653 Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask; 654 break; 655 } 656 case Instruction::Call: 657 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 658 switch (II->getIntrinsicID()) { 659 default: break; 660 case Intrinsic::bswap: { 661 // If the only bits demanded come from one byte of the bswap result, 662 // just shift the input byte into position to eliminate the bswap. 663 unsigned NLZ = DemandedMask.countLeadingZeros(); 664 unsigned NTZ = DemandedMask.countTrailingZeros(); 665 666 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 667 // we need all the bits down to bit 8. Likewise, round NLZ. If we 668 // have 14 leading zeros, round to 8. 669 NLZ &= ~7; 670 NTZ &= ~7; 671 // If we need exactly one byte, we can do this transformation. 672 if (BitWidth-NLZ-NTZ == 8) { 673 unsigned ResultBit = NTZ; 674 unsigned InputBit = BitWidth-NTZ-8; 675 676 // Replace this with either a left or right shift to get the byte into 677 // the right place. 678 Instruction *NewVal; 679 if (InputBit > ResultBit) 680 NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0), 681 ConstantInt::get(I->getType(), InputBit-ResultBit)); 682 else 683 NewVal = BinaryOperator::CreateShl(II->getArgOperand(0), 684 ConstantInt::get(I->getType(), ResultBit-InputBit)); 685 NewVal->takeName(I); 686 return InsertNewInstWith(NewVal, *I); 687 } 688 689 // TODO: Could compute known zero/one bits based on the input. 690 break; 691 } 692 case Intrinsic::fshr: 693 case Intrinsic::fshl: { 694 const APInt *SA; 695 if (!match(I->getOperand(2), m_APInt(SA))) 696 break; 697 698 // Normalize to funnel shift left. APInt shifts of BitWidth are well- 699 // defined, so no need to special-case zero shifts here. 700 uint64_t ShiftAmt = SA->urem(BitWidth); 701 if (II->getIntrinsicID() == Intrinsic::fshr) 702 ShiftAmt = BitWidth - ShiftAmt; 703 704 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt)); 705 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt)); 706 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) || 707 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1)) 708 return I; 709 710 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) | 711 RHSKnown.Zero.lshr(BitWidth - ShiftAmt); 712 Known.One = LHSKnown.One.shl(ShiftAmt) | 713 RHSKnown.One.lshr(BitWidth - ShiftAmt); 714 break; 715 } 716 case Intrinsic::x86_mmx_pmovmskb: 717 case Intrinsic::x86_sse_movmsk_ps: 718 case Intrinsic::x86_sse2_movmsk_pd: 719 case Intrinsic::x86_sse2_pmovmskb_128: 720 case Intrinsic::x86_avx_movmsk_ps_256: 721 case Intrinsic::x86_avx_movmsk_pd_256: 722 case Intrinsic::x86_avx2_pmovmskb: { 723 // MOVMSK copies the vector elements' sign bits to the low bits 724 // and zeros the high bits. 725 unsigned ArgWidth; 726 if (II->getIntrinsicID() == Intrinsic::x86_mmx_pmovmskb) { 727 ArgWidth = 8; // Arg is x86_mmx, but treated as <8 x i8>. 728 } else { 729 auto Arg = II->getArgOperand(0); 730 auto ArgType = cast<VectorType>(Arg->getType()); 731 ArgWidth = ArgType->getNumElements(); 732 } 733 734 // If we don't need any of low bits then return zero, 735 // we know that DemandedMask is non-zero already. 736 APInt DemandedElts = DemandedMask.zextOrTrunc(ArgWidth); 737 if (DemandedElts.isNullValue()) 738 return ConstantInt::getNullValue(VTy); 739 740 // We know that the upper bits are set to zero. 741 Known.Zero.setBitsFrom(ArgWidth); 742 return nullptr; 743 } 744 case Intrinsic::x86_sse42_crc32_64_64: 745 Known.Zero.setBitsFrom(32); 746 return nullptr; 747 } 748 } 749 computeKnownBits(V, Known, Depth, CxtI); 750 break; 751 } 752 753 // If the client is only demanding bits that we know, return the known 754 // constant. 755 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 756 return Constant::getIntegerValue(VTy, Known.One); 757 return nullptr; 758 } 759 760 /// Helper routine of SimplifyDemandedUseBits. It computes Known 761 /// bits. It also tries to handle simplifications that can be done based on 762 /// DemandedMask, but without modifying the Instruction. 763 Value *InstCombiner::SimplifyMultipleUseDemandedBits(Instruction *I, 764 const APInt &DemandedMask, 765 KnownBits &Known, 766 unsigned Depth, 767 Instruction *CxtI) { 768 unsigned BitWidth = DemandedMask.getBitWidth(); 769 Type *ITy = I->getType(); 770 771 KnownBits LHSKnown(BitWidth); 772 KnownBits RHSKnown(BitWidth); 773 774 // Despite the fact that we can't simplify this instruction in all User's 775 // context, we can at least compute the known bits, and we can 776 // do simplifications that apply to *just* the one user if we know that 777 // this instruction has a simpler value in that context. 778 switch (I->getOpcode()) { 779 case Instruction::And: { 780 // If either the LHS or the RHS are Zero, the result is zero. 781 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 782 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 783 CxtI); 784 785 // Output known-0 are known to be clear if zero in either the LHS | RHS. 786 APInt IKnownZero = RHSKnown.Zero | LHSKnown.Zero; 787 // Output known-1 bits are only known if set in both the LHS & RHS. 788 APInt IKnownOne = RHSKnown.One & LHSKnown.One; 789 790 // If the client is only demanding bits that we know, return the known 791 // constant. 792 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 793 return Constant::getIntegerValue(ITy, IKnownOne); 794 795 // If all of the demanded bits are known 1 on one side, return the other. 796 // These bits cannot contribute to the result of the 'and' in this 797 // context. 798 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 799 return I->getOperand(0); 800 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 801 return I->getOperand(1); 802 803 Known.Zero = std::move(IKnownZero); 804 Known.One = std::move(IKnownOne); 805 break; 806 } 807 case Instruction::Or: { 808 // We can simplify (X|Y) -> X or Y in the user's context if we know that 809 // only bits from X or Y are demanded. 810 811 // If either the LHS or the RHS are One, the result is One. 812 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 813 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 814 CxtI); 815 816 // Output known-0 bits are only known if clear in both the LHS & RHS. 817 APInt IKnownZero = RHSKnown.Zero & LHSKnown.Zero; 818 // Output known-1 are known to be set if set in either the LHS | RHS. 819 APInt IKnownOne = RHSKnown.One | LHSKnown.One; 820 821 // If the client is only demanding bits that we know, return the known 822 // constant. 823 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 824 return Constant::getIntegerValue(ITy, IKnownOne); 825 826 // If all of the demanded bits are known zero on one side, return the 827 // other. These bits cannot contribute to the result of the 'or' in this 828 // context. 829 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 830 return I->getOperand(0); 831 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 832 return I->getOperand(1); 833 834 Known.Zero = std::move(IKnownZero); 835 Known.One = std::move(IKnownOne); 836 break; 837 } 838 case Instruction::Xor: { 839 // We can simplify (X^Y) -> X or Y in the user's context if we know that 840 // only bits from X or Y are demanded. 841 842 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 843 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 844 CxtI); 845 846 // Output known-0 bits are known if clear or set in both the LHS & RHS. 847 APInt IKnownZero = (RHSKnown.Zero & LHSKnown.Zero) | 848 (RHSKnown.One & LHSKnown.One); 849 // Output known-1 are known to be set if set in only one of the LHS, RHS. 850 APInt IKnownOne = (RHSKnown.Zero & LHSKnown.One) | 851 (RHSKnown.One & LHSKnown.Zero); 852 853 // If the client is only demanding bits that we know, return the known 854 // constant. 855 if (DemandedMask.isSubsetOf(IKnownZero|IKnownOne)) 856 return Constant::getIntegerValue(ITy, IKnownOne); 857 858 // If all of the demanded bits are known zero on one side, return the 859 // other. 860 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 861 return I->getOperand(0); 862 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 863 return I->getOperand(1); 864 865 // Output known-0 bits are known if clear or set in both the LHS & RHS. 866 Known.Zero = std::move(IKnownZero); 867 // Output known-1 are known to be set if set in only one of the LHS, RHS. 868 Known.One = std::move(IKnownOne); 869 break; 870 } 871 default: 872 // Compute the Known bits to simplify things downstream. 873 computeKnownBits(I, Known, Depth, CxtI); 874 875 // If this user is only demanding bits that we know, return the known 876 // constant. 877 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 878 return Constant::getIntegerValue(ITy, Known.One); 879 880 break; 881 } 882 883 return nullptr; 884 } 885 886 887 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify 888 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into 889 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign 890 /// of "C2-C1". 891 /// 892 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1, 893 /// ..., bn}, without considering the specific value X is holding. 894 /// This transformation is legal iff one of following conditions is hold: 895 /// 1) All the bit in S are 0, in this case E1 == E2. 896 /// 2) We don't care those bits in S, per the input DemandedMask. 897 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the 898 /// rest bits. 899 /// 900 /// Currently we only test condition 2). 901 /// 902 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was 903 /// not successful. 904 Value * 905 InstCombiner::simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, 906 Instruction *Shl, const APInt &ShlOp1, 907 const APInt &DemandedMask, 908 KnownBits &Known) { 909 if (!ShlOp1 || !ShrOp1) 910 return nullptr; // No-op. 911 912 Value *VarX = Shr->getOperand(0); 913 Type *Ty = VarX->getType(); 914 unsigned BitWidth = Ty->getScalarSizeInBits(); 915 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth)) 916 return nullptr; // Undef. 917 918 unsigned ShlAmt = ShlOp1.getZExtValue(); 919 unsigned ShrAmt = ShrOp1.getZExtValue(); 920 921 Known.One.clearAllBits(); 922 Known.Zero.setLowBits(ShlAmt - 1); 923 Known.Zero &= DemandedMask; 924 925 APInt BitMask1(APInt::getAllOnesValue(BitWidth)); 926 APInt BitMask2(APInt::getAllOnesValue(BitWidth)); 927 928 bool isLshr = (Shr->getOpcode() == Instruction::LShr); 929 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) : 930 (BitMask1.ashr(ShrAmt) << ShlAmt); 931 932 if (ShrAmt <= ShlAmt) { 933 BitMask2 <<= (ShlAmt - ShrAmt); 934 } else { 935 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt): 936 BitMask2.ashr(ShrAmt - ShlAmt); 937 } 938 939 // Check if condition-2 (see the comment to this function) is satified. 940 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) { 941 if (ShrAmt == ShlAmt) 942 return VarX; 943 944 if (!Shr->hasOneUse()) 945 return nullptr; 946 947 BinaryOperator *New; 948 if (ShrAmt < ShlAmt) { 949 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt); 950 New = BinaryOperator::CreateShl(VarX, Amt); 951 BinaryOperator *Orig = cast<BinaryOperator>(Shl); 952 New->setHasNoSignedWrap(Orig->hasNoSignedWrap()); 953 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap()); 954 } else { 955 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt); 956 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) : 957 BinaryOperator::CreateAShr(VarX, Amt); 958 if (cast<BinaryOperator>(Shr)->isExact()) 959 New->setIsExact(true); 960 } 961 962 return InsertNewInstWith(New, *Shl); 963 } 964 965 return nullptr; 966 } 967 968 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics. 969 Value *InstCombiner::simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II, 970 APInt DemandedElts, 971 int DMaskIdx, 972 int TFCIdx) { 973 unsigned VWidth = II->getType()->getVectorNumElements(); 974 if (VWidth == 1) 975 return nullptr; 976 977 // Need to change to new instruction format 978 bool TFELWEEnabled = false; 979 if (TFCIdx > 0) { 980 if (ConstantInt *TFC = dyn_cast<ConstantInt>(II->getArgOperand(TFCIdx))) 981 TFELWEEnabled = TFC->getZExtValue() & 0x1 // TFE 982 || TFC->getZExtValue() & 0x2; // LWE 983 } 984 985 if (TFELWEEnabled) 986 return nullptr; // TFE not yet supported 987 988 ConstantInt *NewDMask = nullptr; 989 990 if (DMaskIdx < 0) { 991 // Pretend that a prefix of elements is demanded to simplify the code 992 // below. 993 DemandedElts = (1 << DemandedElts.getActiveBits()) - 1; 994 } else { 995 ConstantInt *DMask = dyn_cast<ConstantInt>(II->getArgOperand(DMaskIdx)); 996 if (!DMask) 997 return nullptr; // non-constant dmask is not supported by codegen 998 999 unsigned DMaskVal = DMask->getZExtValue() & 0xf; 1000 1001 // Mask off values that are undefined because the dmask doesn't cover them 1002 DemandedElts &= (1 << countPopulation(DMaskVal)) - 1; 1003 1004 unsigned NewDMaskVal = 0; 1005 unsigned OrigLoadIdx = 0; 1006 for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) { 1007 const unsigned Bit = 1 << SrcIdx; 1008 if (!!(DMaskVal & Bit)) { 1009 if (!!DemandedElts[OrigLoadIdx]) 1010 NewDMaskVal |= Bit; 1011 OrigLoadIdx++; 1012 } 1013 } 1014 1015 if (DMaskVal != NewDMaskVal) 1016 NewDMask = ConstantInt::get(DMask->getType(), NewDMaskVal); 1017 } 1018 1019 // TODO: Handle 3 vectors when supported in code gen. 1020 unsigned NewNumElts = PowerOf2Ceil(DemandedElts.countPopulation()); 1021 if (!NewNumElts) 1022 return UndefValue::get(II->getType()); 1023 1024 if (NewNumElts >= VWidth && DemandedElts.isMask()) { 1025 if (NewDMask) 1026 II->setArgOperand(DMaskIdx, NewDMask); 1027 return nullptr; 1028 } 1029 1030 // Determine the overload types of the original intrinsic. 1031 auto IID = II->getIntrinsicID(); 1032 SmallVector<Intrinsic::IITDescriptor, 16> Table; 1033 getIntrinsicInfoTableEntries(IID, Table); 1034 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1035 1036 FunctionType *FTy = II->getCalledFunction()->getFunctionType(); 1037 SmallVector<Type *, 6> OverloadTys; 1038 Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, OverloadTys); 1039 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1040 Intrinsic::matchIntrinsicType(FTy->getParamType(i), TableRef, OverloadTys); 1041 1042 // Get the new return type overload of the intrinsic. 1043 Module *M = II->getParent()->getParent()->getParent(); 1044 Type *EltTy = II->getType()->getVectorElementType(); 1045 Type *NewTy = (NewNumElts == 1) ? EltTy : VectorType::get(EltTy, NewNumElts); 1046 1047 OverloadTys[0] = NewTy; 1048 Function *NewIntrin = Intrinsic::getDeclaration(M, IID, OverloadTys); 1049 1050 SmallVector<Value *, 16> Args; 1051 for (unsigned I = 0, E = II->getNumArgOperands(); I != E; ++I) 1052 Args.push_back(II->getArgOperand(I)); 1053 1054 if (NewDMask) 1055 Args[DMaskIdx] = NewDMask; 1056 1057 IRBuilderBase::InsertPointGuard Guard(Builder); 1058 Builder.SetInsertPoint(II); 1059 1060 CallInst *NewCall = Builder.CreateCall(NewIntrin, Args); 1061 NewCall->takeName(II); 1062 NewCall->copyMetadata(*II); 1063 1064 if (NewNumElts == 1) { 1065 return Builder.CreateInsertElement(UndefValue::get(II->getType()), NewCall, 1066 DemandedElts.countTrailingZeros()); 1067 } 1068 1069 SmallVector<uint32_t, 8> EltMask; 1070 unsigned NewLoadIdx = 0; 1071 for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) { 1072 if (!!DemandedElts[OrigLoadIdx]) 1073 EltMask.push_back(NewLoadIdx++); 1074 else 1075 EltMask.push_back(NewNumElts); 1076 } 1077 1078 Value *Shuffle = 1079 Builder.CreateShuffleVector(NewCall, UndefValue::get(NewTy), EltMask); 1080 1081 return Shuffle; 1082 } 1083 1084 /// The specified value produces a vector with any number of elements. 1085 /// DemandedElts contains the set of elements that are actually used by the 1086 /// caller. This method analyzes which elements of the operand are undef and 1087 /// returns that information in UndefElts. 1088 /// 1089 /// If the information about demanded elements can be used to simplify the 1090 /// operation, the operation is simplified, then the resultant value is 1091 /// returned. This returns null if no change was made. 1092 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, 1093 APInt &UndefElts, 1094 unsigned Depth) { 1095 unsigned VWidth = V->getType()->getVectorNumElements(); 1096 APInt EltMask(APInt::getAllOnesValue(VWidth)); 1097 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!"); 1098 1099 if (isa<UndefValue>(V)) { 1100 // If the entire vector is undefined, just return this info. 1101 UndefElts = EltMask; 1102 return nullptr; 1103 } 1104 1105 if (DemandedElts.isNullValue()) { // If nothing is demanded, provide undef. 1106 UndefElts = EltMask; 1107 return UndefValue::get(V->getType()); 1108 } 1109 1110 UndefElts = 0; 1111 1112 if (auto *C = dyn_cast<Constant>(V)) { 1113 // Check if this is identity. If so, return 0 since we are not simplifying 1114 // anything. 1115 if (DemandedElts.isAllOnesValue()) 1116 return nullptr; 1117 1118 Type *EltTy = cast<VectorType>(V->getType())->getElementType(); 1119 Constant *Undef = UndefValue::get(EltTy); 1120 SmallVector<Constant*, 16> Elts; 1121 for (unsigned i = 0; i != VWidth; ++i) { 1122 if (!DemandedElts[i]) { // If not demanded, set to undef. 1123 Elts.push_back(Undef); 1124 UndefElts.setBit(i); 1125 continue; 1126 } 1127 1128 Constant *Elt = C->getAggregateElement(i); 1129 if (!Elt) return nullptr; 1130 1131 if (isa<UndefValue>(Elt)) { // Already undef. 1132 Elts.push_back(Undef); 1133 UndefElts.setBit(i); 1134 } else { // Otherwise, defined. 1135 Elts.push_back(Elt); 1136 } 1137 } 1138 1139 // If we changed the constant, return it. 1140 Constant *NewCV = ConstantVector::get(Elts); 1141 return NewCV != C ? NewCV : nullptr; 1142 } 1143 1144 // Limit search depth. 1145 if (Depth == 10) 1146 return nullptr; 1147 1148 // If multiple users are using the root value, proceed with 1149 // simplification conservatively assuming that all elements 1150 // are needed. 1151 if (!V->hasOneUse()) { 1152 // Quit if we find multiple users of a non-root value though. 1153 // They'll be handled when it's their turn to be visited by 1154 // the main instcombine process. 1155 if (Depth != 0) 1156 // TODO: Just compute the UndefElts information recursively. 1157 return nullptr; 1158 1159 // Conservatively assume that all elements are needed. 1160 DemandedElts = EltMask; 1161 } 1162 1163 Instruction *I = dyn_cast<Instruction>(V); 1164 if (!I) return nullptr; // Only analyze instructions. 1165 1166 bool MadeChange = false; 1167 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum, 1168 APInt Demanded, APInt &Undef) { 1169 auto *II = dyn_cast<IntrinsicInst>(Inst); 1170 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum); 1171 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) { 1172 if (II) 1173 II->setArgOperand(OpNum, V); 1174 else 1175 Inst->setOperand(OpNum, V); 1176 MadeChange = true; 1177 } 1178 }; 1179 1180 APInt UndefElts2(VWidth, 0); 1181 APInt UndefElts3(VWidth, 0); 1182 switch (I->getOpcode()) { 1183 default: break; 1184 1185 case Instruction::GetElementPtr: { 1186 // Conservatively track the demanded elements back through any vector 1187 // operands we may have. We know there must be at least one, or we 1188 // wouldn't have a vector result to get here. Note that we intentionally 1189 // merge the undef bits here since gepping with either an undef base or 1190 // index results in undef. 1191 for (unsigned i = 0; i < I->getNumOperands(); i++) 1192 if (I->getOperand(i)->getType()->isVectorTy()) 1193 simplifyAndSetOp(I, i, DemandedElts, UndefElts); 1194 1195 break; 1196 } 1197 case Instruction::InsertElement: { 1198 // If this is a variable index, we don't know which element it overwrites. 1199 // demand exactly the same input as we produce. 1200 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2)); 1201 if (!Idx) { 1202 // Note that we can't propagate undef elt info, because we don't know 1203 // which elt is getting updated. 1204 simplifyAndSetOp(I, 0, DemandedElts, UndefElts2); 1205 break; 1206 } 1207 1208 // The element inserted overwrites whatever was there, so the input demanded 1209 // set is simpler than the output set. 1210 unsigned IdxNo = Idx->getZExtValue(); 1211 APInt PreInsertDemandedElts = DemandedElts; 1212 if (IdxNo < VWidth) 1213 PreInsertDemandedElts.clearBit(IdxNo); 1214 1215 simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts); 1216 1217 // If this is inserting an element that isn't demanded, remove this 1218 // insertelement. 1219 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) { 1220 Worklist.Add(I); 1221 return I->getOperand(0); 1222 } 1223 1224 // The inserted element is defined. 1225 UndefElts.clearBit(IdxNo); 1226 break; 1227 } 1228 case Instruction::ShuffleVector: { 1229 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); 1230 unsigned LHSVWidth = 1231 Shuffle->getOperand(0)->getType()->getVectorNumElements(); 1232 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0); 1233 for (unsigned i = 0; i < VWidth; i++) { 1234 if (DemandedElts[i]) { 1235 unsigned MaskVal = Shuffle->getMaskValue(i); 1236 if (MaskVal != -1u) { 1237 assert(MaskVal < LHSVWidth * 2 && 1238 "shufflevector mask index out of range!"); 1239 if (MaskVal < LHSVWidth) 1240 LeftDemanded.setBit(MaskVal); 1241 else 1242 RightDemanded.setBit(MaskVal - LHSVWidth); 1243 } 1244 } 1245 } 1246 1247 APInt LHSUndefElts(LHSVWidth, 0); 1248 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts); 1249 1250 APInt RHSUndefElts(LHSVWidth, 0); 1251 simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts); 1252 1253 bool NewUndefElts = false; 1254 unsigned LHSIdx = -1u, LHSValIdx = -1u; 1255 unsigned RHSIdx = -1u, RHSValIdx = -1u; 1256 bool LHSUniform = true; 1257 bool RHSUniform = true; 1258 for (unsigned i = 0; i < VWidth; i++) { 1259 unsigned MaskVal = Shuffle->getMaskValue(i); 1260 if (MaskVal == -1u) { 1261 UndefElts.setBit(i); 1262 } else if (!DemandedElts[i]) { 1263 NewUndefElts = true; 1264 UndefElts.setBit(i); 1265 } else if (MaskVal < LHSVWidth) { 1266 if (LHSUndefElts[MaskVal]) { 1267 NewUndefElts = true; 1268 UndefElts.setBit(i); 1269 } else { 1270 LHSIdx = LHSIdx == -1u ? i : LHSVWidth; 1271 LHSValIdx = LHSValIdx == -1u ? MaskVal : LHSVWidth; 1272 LHSUniform = LHSUniform && (MaskVal == i); 1273 } 1274 } else { 1275 if (RHSUndefElts[MaskVal - LHSVWidth]) { 1276 NewUndefElts = true; 1277 UndefElts.setBit(i); 1278 } else { 1279 RHSIdx = RHSIdx == -1u ? i : LHSVWidth; 1280 RHSValIdx = RHSValIdx == -1u ? MaskVal - LHSVWidth : LHSVWidth; 1281 RHSUniform = RHSUniform && (MaskVal - LHSVWidth == i); 1282 } 1283 } 1284 } 1285 1286 // Try to transform shuffle with constant vector and single element from 1287 // this constant vector to single insertelement instruction. 1288 // shufflevector V, C, <v1, v2, .., ci, .., vm> -> 1289 // insertelement V, C[ci], ci-n 1290 if (LHSVWidth == Shuffle->getType()->getNumElements()) { 1291 Value *Op = nullptr; 1292 Constant *Value = nullptr; 1293 unsigned Idx = -1u; 1294 1295 // Find constant vector with the single element in shuffle (LHS or RHS). 1296 if (LHSIdx < LHSVWidth && RHSUniform) { 1297 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) { 1298 Op = Shuffle->getOperand(1); 1299 Value = CV->getOperand(LHSValIdx); 1300 Idx = LHSIdx; 1301 } 1302 } 1303 if (RHSIdx < LHSVWidth && LHSUniform) { 1304 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) { 1305 Op = Shuffle->getOperand(0); 1306 Value = CV->getOperand(RHSValIdx); 1307 Idx = RHSIdx; 1308 } 1309 } 1310 // Found constant vector with single element - convert to insertelement. 1311 if (Op && Value) { 1312 Instruction *New = InsertElementInst::Create( 1313 Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx), 1314 Shuffle->getName()); 1315 InsertNewInstWith(New, *Shuffle); 1316 return New; 1317 } 1318 } 1319 if (NewUndefElts) { 1320 // Add additional discovered undefs. 1321 SmallVector<Constant*, 16> Elts; 1322 for (unsigned i = 0; i < VWidth; ++i) { 1323 if (UndefElts[i]) 1324 Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext()))); 1325 else 1326 Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()), 1327 Shuffle->getMaskValue(i))); 1328 } 1329 I->setOperand(2, ConstantVector::get(Elts)); 1330 MadeChange = true; 1331 } 1332 break; 1333 } 1334 case Instruction::Select: { 1335 // If this is a vector select, try to transform the select condition based 1336 // on the current demanded elements. 1337 SelectInst *Sel = cast<SelectInst>(I); 1338 if (Sel->getCondition()->getType()->isVectorTy()) { 1339 // TODO: We are not doing anything with UndefElts based on this call. 1340 // It is overwritten below based on the other select operands. If an 1341 // element of the select condition is known undef, then we are free to 1342 // choose the output value from either arm of the select. If we know that 1343 // one of those values is undef, then the output can be undef. 1344 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1345 } 1346 1347 // Next, see if we can transform the arms of the select. 1348 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts); 1349 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) { 1350 for (unsigned i = 0; i < VWidth; i++) { 1351 // isNullValue() always returns false when called on a ConstantExpr. 1352 // Skip constant expressions to avoid propagating incorrect information. 1353 Constant *CElt = CV->getAggregateElement(i); 1354 if (isa<ConstantExpr>(CElt)) 1355 continue; 1356 // TODO: If a select condition element is undef, we can demand from 1357 // either side. If one side is known undef, choosing that side would 1358 // propagate undef. 1359 if (CElt->isNullValue()) 1360 DemandedLHS.clearBit(i); 1361 else 1362 DemandedRHS.clearBit(i); 1363 } 1364 } 1365 1366 simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2); 1367 simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3); 1368 1369 // Output elements are undefined if the element from each arm is undefined. 1370 // TODO: This can be improved. See comment in select condition handling. 1371 UndefElts = UndefElts2 & UndefElts3; 1372 break; 1373 } 1374 case Instruction::BitCast: { 1375 // Vector->vector casts only. 1376 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType()); 1377 if (!VTy) break; 1378 unsigned InVWidth = VTy->getNumElements(); 1379 APInt InputDemandedElts(InVWidth, 0); 1380 UndefElts2 = APInt(InVWidth, 0); 1381 unsigned Ratio; 1382 1383 if (VWidth == InVWidth) { 1384 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same 1385 // elements as are demanded of us. 1386 Ratio = 1; 1387 InputDemandedElts = DemandedElts; 1388 } else if ((VWidth % InVWidth) == 0) { 1389 // If the number of elements in the output is a multiple of the number of 1390 // elements in the input then an input element is live if any of the 1391 // corresponding output elements are live. 1392 Ratio = VWidth / InVWidth; 1393 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1394 if (DemandedElts[OutIdx]) 1395 InputDemandedElts.setBit(OutIdx / Ratio); 1396 } else if ((InVWidth % VWidth) == 0) { 1397 // If the number of elements in the input is a multiple of the number of 1398 // elements in the output then an input element is live if the 1399 // corresponding output element is live. 1400 Ratio = InVWidth / VWidth; 1401 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx) 1402 if (DemandedElts[InIdx / Ratio]) 1403 InputDemandedElts.setBit(InIdx); 1404 } else { 1405 // Unsupported so far. 1406 break; 1407 } 1408 1409 simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2); 1410 1411 if (VWidth == InVWidth) { 1412 UndefElts = UndefElts2; 1413 } else if ((VWidth % InVWidth) == 0) { 1414 // If the number of elements in the output is a multiple of the number of 1415 // elements in the input then an output element is undef if the 1416 // corresponding input element is undef. 1417 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1418 if (UndefElts2[OutIdx / Ratio]) 1419 UndefElts.setBit(OutIdx); 1420 } else if ((InVWidth % VWidth) == 0) { 1421 // If the number of elements in the input is a multiple of the number of 1422 // elements in the output then an output element is undef if all of the 1423 // corresponding input elements are undef. 1424 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) { 1425 APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio); 1426 if (SubUndef.countPopulation() == Ratio) 1427 UndefElts.setBit(OutIdx); 1428 } 1429 } else { 1430 llvm_unreachable("Unimp"); 1431 } 1432 break; 1433 } 1434 case Instruction::FPTrunc: 1435 case Instruction::FPExt: 1436 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1437 break; 1438 1439 case Instruction::Call: { 1440 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1441 if (!II) break; 1442 switch (II->getIntrinsicID()) { 1443 case Intrinsic::x86_xop_vfrcz_ss: 1444 case Intrinsic::x86_xop_vfrcz_sd: 1445 // The instructions for these intrinsics are speced to zero upper bits not 1446 // pass them through like other scalar intrinsics. So we shouldn't just 1447 // use Arg0 if DemandedElts[0] is clear like we do for other intrinsics. 1448 // Instead we should return a zero vector. 1449 if (!DemandedElts[0]) { 1450 Worklist.Add(II); 1451 return ConstantAggregateZero::get(II->getType()); 1452 } 1453 1454 // Only the lower element is used. 1455 DemandedElts = 1; 1456 simplifyAndSetOp(II, 0, DemandedElts, UndefElts); 1457 1458 // Only the lower element is undefined. The high elements are zero. 1459 UndefElts = UndefElts[0]; 1460 break; 1461 1462 // Unary scalar-as-vector operations that work column-wise. 1463 case Intrinsic::x86_sse_rcp_ss: 1464 case Intrinsic::x86_sse_rsqrt_ss: 1465 simplifyAndSetOp(II, 0, DemandedElts, UndefElts); 1466 1467 // If lowest element of a scalar op isn't used then use Arg0. 1468 if (!DemandedElts[0]) { 1469 Worklist.Add(II); 1470 return II->getArgOperand(0); 1471 } 1472 // TODO: If only low elt lower SQRT to FSQRT (with rounding/exceptions 1473 // checks). 1474 break; 1475 1476 // Binary scalar-as-vector operations that work column-wise. The high 1477 // elements come from operand 0. The low element is a function of both 1478 // operands. 1479 case Intrinsic::x86_sse_min_ss: 1480 case Intrinsic::x86_sse_max_ss: 1481 case Intrinsic::x86_sse_cmp_ss: 1482 case Intrinsic::x86_sse2_min_sd: 1483 case Intrinsic::x86_sse2_max_sd: 1484 case Intrinsic::x86_sse2_cmp_sd: { 1485 simplifyAndSetOp(II, 0, DemandedElts, UndefElts); 1486 1487 // If lowest element of a scalar op isn't used then use Arg0. 1488 if (!DemandedElts[0]) { 1489 Worklist.Add(II); 1490 return II->getArgOperand(0); 1491 } 1492 1493 // Only lower element is used for operand 1. 1494 DemandedElts = 1; 1495 simplifyAndSetOp(II, 1, DemandedElts, UndefElts2); 1496 1497 // Lower element is undefined if both lower elements are undefined. 1498 // Consider things like undef&0. The result is known zero, not undef. 1499 if (!UndefElts2[0]) 1500 UndefElts.clearBit(0); 1501 1502 break; 1503 } 1504 1505 // Binary scalar-as-vector operations that work column-wise. The high 1506 // elements come from operand 0 and the low element comes from operand 1. 1507 case Intrinsic::x86_sse41_round_ss: 1508 case Intrinsic::x86_sse41_round_sd: { 1509 // Don't use the low element of operand 0. 1510 APInt DemandedElts2 = DemandedElts; 1511 DemandedElts2.clearBit(0); 1512 simplifyAndSetOp(II, 0, DemandedElts2, UndefElts); 1513 1514 // If lowest element of a scalar op isn't used then use Arg0. 1515 if (!DemandedElts[0]) { 1516 Worklist.Add(II); 1517 return II->getArgOperand(0); 1518 } 1519 1520 // Only lower element is used for operand 1. 1521 DemandedElts = 1; 1522 simplifyAndSetOp(II, 1, DemandedElts, UndefElts2); 1523 1524 // Take the high undef elements from operand 0 and take the lower element 1525 // from operand 1. 1526 UndefElts.clearBit(0); 1527 UndefElts |= UndefElts2[0]; 1528 break; 1529 } 1530 1531 // Three input scalar-as-vector operations that work column-wise. The high 1532 // elements come from operand 0 and the low element is a function of all 1533 // three inputs. 1534 case Intrinsic::x86_avx512_mask_add_ss_round: 1535 case Intrinsic::x86_avx512_mask_div_ss_round: 1536 case Intrinsic::x86_avx512_mask_mul_ss_round: 1537 case Intrinsic::x86_avx512_mask_sub_ss_round: 1538 case Intrinsic::x86_avx512_mask_max_ss_round: 1539 case Intrinsic::x86_avx512_mask_min_ss_round: 1540 case Intrinsic::x86_avx512_mask_add_sd_round: 1541 case Intrinsic::x86_avx512_mask_div_sd_round: 1542 case Intrinsic::x86_avx512_mask_mul_sd_round: 1543 case Intrinsic::x86_avx512_mask_sub_sd_round: 1544 case Intrinsic::x86_avx512_mask_max_sd_round: 1545 case Intrinsic::x86_avx512_mask_min_sd_round: 1546 simplifyAndSetOp(II, 0, DemandedElts, UndefElts); 1547 1548 // If lowest element of a scalar op isn't used then use Arg0. 1549 if (!DemandedElts[0]) { 1550 Worklist.Add(II); 1551 return II->getArgOperand(0); 1552 } 1553 1554 // Only lower element is used for operand 1 and 2. 1555 DemandedElts = 1; 1556 simplifyAndSetOp(II, 1, DemandedElts, UndefElts2); 1557 simplifyAndSetOp(II, 2, DemandedElts, UndefElts3); 1558 1559 // Lower element is undefined if all three lower elements are undefined. 1560 // Consider things like undef&0. The result is known zero, not undef. 1561 if (!UndefElts2[0] || !UndefElts3[0]) 1562 UndefElts.clearBit(0); 1563 1564 break; 1565 1566 case Intrinsic::x86_sse2_packssdw_128: 1567 case Intrinsic::x86_sse2_packsswb_128: 1568 case Intrinsic::x86_sse2_packuswb_128: 1569 case Intrinsic::x86_sse41_packusdw: 1570 case Intrinsic::x86_avx2_packssdw: 1571 case Intrinsic::x86_avx2_packsswb: 1572 case Intrinsic::x86_avx2_packusdw: 1573 case Intrinsic::x86_avx2_packuswb: 1574 case Intrinsic::x86_avx512_packssdw_512: 1575 case Intrinsic::x86_avx512_packsswb_512: 1576 case Intrinsic::x86_avx512_packusdw_512: 1577 case Intrinsic::x86_avx512_packuswb_512: { 1578 auto *Ty0 = II->getArgOperand(0)->getType(); 1579 unsigned InnerVWidth = Ty0->getVectorNumElements(); 1580 assert(VWidth == (InnerVWidth * 2) && "Unexpected input size"); 1581 1582 unsigned NumLanes = Ty0->getPrimitiveSizeInBits() / 128; 1583 unsigned VWidthPerLane = VWidth / NumLanes; 1584 unsigned InnerVWidthPerLane = InnerVWidth / NumLanes; 1585 1586 // Per lane, pack the elements of the first input and then the second. 1587 // e.g. 1588 // v8i16 PACK(v4i32 X, v4i32 Y) - (X[0..3],Y[0..3]) 1589 // v32i8 PACK(v16i16 X, v16i16 Y) - (X[0..7],Y[0..7]),(X[8..15],Y[8..15]) 1590 for (int OpNum = 0; OpNum != 2; ++OpNum) { 1591 APInt OpDemandedElts(InnerVWidth, 0); 1592 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1593 unsigned LaneIdx = Lane * VWidthPerLane; 1594 for (unsigned Elt = 0; Elt != InnerVWidthPerLane; ++Elt) { 1595 unsigned Idx = LaneIdx + Elt + InnerVWidthPerLane * OpNum; 1596 if (DemandedElts[Idx]) 1597 OpDemandedElts.setBit((Lane * InnerVWidthPerLane) + Elt); 1598 } 1599 } 1600 1601 // Demand elements from the operand. 1602 APInt OpUndefElts(InnerVWidth, 0); 1603 simplifyAndSetOp(II, OpNum, OpDemandedElts, OpUndefElts); 1604 1605 // Pack the operand's UNDEF elements, one lane at a time. 1606 OpUndefElts = OpUndefElts.zext(VWidth); 1607 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1608 APInt LaneElts = OpUndefElts.lshr(InnerVWidthPerLane * Lane); 1609 LaneElts = LaneElts.getLoBits(InnerVWidthPerLane); 1610 LaneElts <<= InnerVWidthPerLane * (2 * Lane + OpNum); 1611 UndefElts |= LaneElts; 1612 } 1613 } 1614 break; 1615 } 1616 1617 // PSHUFB 1618 case Intrinsic::x86_ssse3_pshuf_b_128: 1619 case Intrinsic::x86_avx2_pshuf_b: 1620 case Intrinsic::x86_avx512_pshuf_b_512: 1621 // PERMILVAR 1622 case Intrinsic::x86_avx_vpermilvar_ps: 1623 case Intrinsic::x86_avx_vpermilvar_ps_256: 1624 case Intrinsic::x86_avx512_vpermilvar_ps_512: 1625 case Intrinsic::x86_avx_vpermilvar_pd: 1626 case Intrinsic::x86_avx_vpermilvar_pd_256: 1627 case Intrinsic::x86_avx512_vpermilvar_pd_512: 1628 // PERMV 1629 case Intrinsic::x86_avx2_permd: 1630 case Intrinsic::x86_avx2_permps: { 1631 simplifyAndSetOp(II, 1, DemandedElts, UndefElts); 1632 break; 1633 } 1634 1635 // SSE4A instructions leave the upper 64-bits of the 128-bit result 1636 // in an undefined state. 1637 case Intrinsic::x86_sse4a_extrq: 1638 case Intrinsic::x86_sse4a_extrqi: 1639 case Intrinsic::x86_sse4a_insertq: 1640 case Intrinsic::x86_sse4a_insertqi: 1641 UndefElts.setHighBits(VWidth / 2); 1642 break; 1643 case Intrinsic::amdgcn_buffer_load: 1644 case Intrinsic::amdgcn_buffer_load_format: 1645 case Intrinsic::amdgcn_raw_buffer_load: 1646 case Intrinsic::amdgcn_raw_buffer_load_format: 1647 case Intrinsic::amdgcn_struct_buffer_load: 1648 case Intrinsic::amdgcn_struct_buffer_load_format: 1649 return simplifyAMDGCNMemoryIntrinsicDemanded(II, DemandedElts); 1650 default: { 1651 if (getAMDGPUImageDMaskIntrinsic(II->getIntrinsicID())) 1652 return simplifyAMDGCNMemoryIntrinsicDemanded( 1653 II, DemandedElts, 0, II->getNumArgOperands() - 2); 1654 1655 break; 1656 } 1657 } // switch on IntrinsicID 1658 break; 1659 } // case Call 1660 } // switch on Opcode 1661 1662 // TODO: We bail completely on integer div/rem and shifts because they have 1663 // UB/poison potential, but that should be refined. 1664 BinaryOperator *BO; 1665 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) { 1666 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1667 simplifyAndSetOp(I, 1, DemandedElts, UndefElts2); 1668 1669 // Any change to an instruction with potential poison must clear those flags 1670 // because we can not guarantee those constraints now. Other analysis may 1671 // determine that it is safe to re-apply the flags. 1672 if (MadeChange) 1673 BO->dropPoisonGeneratingFlags(); 1674 1675 // Output elements are undefined if both are undefined. Consider things 1676 // like undef & 0. The result is known zero, not undef. 1677 UndefElts &= UndefElts2; 1678 } 1679 1680 return MadeChange ? I : nullptr; 1681 } 1682