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/TargetTransformInfo.h" 16 #include "llvm/Analysis/ValueTracking.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/PatternMatch.h" 19 #include "llvm/Support/KnownBits.h" 20 #include "llvm/Transforms/InstCombine/InstCombiner.h" 21 22 using namespace llvm; 23 using namespace llvm::PatternMatch; 24 25 #define DEBUG_TYPE "instcombine" 26 27 /// Check to see if the specified operand of the specified instruction is a 28 /// constant integer. If so, check to see if there are any bits set in the 29 /// constant that are not demanded. If so, shrink the constant and return true. 30 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 31 const APInt &Demanded) { 32 assert(I && "No instruction?"); 33 assert(OpNo < I->getNumOperands() && "Operand index too large"); 34 35 // The operand must be a constant integer or splat integer. 36 Value *Op = I->getOperand(OpNo); 37 const APInt *C; 38 if (!match(Op, m_APInt(C))) 39 return false; 40 41 // If there are no bits set that aren't demanded, nothing to do. 42 if (C->isSubsetOf(Demanded)) 43 return false; 44 45 // This instruction is producing bits that are not demanded. Shrink the RHS. 46 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded)); 47 48 return true; 49 } 50 51 52 53 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if 54 /// the instruction has any properties that allow us to simplify its operands. 55 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) { 56 unsigned BitWidth = Inst.getType()->getScalarSizeInBits(); 57 KnownBits Known(BitWidth); 58 APInt DemandedMask(APInt::getAllOnesValue(BitWidth)); 59 60 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known, 61 0, &Inst); 62 if (!V) return false; 63 if (V == &Inst) return true; 64 replaceInstUsesWith(Inst, V); 65 return true; 66 } 67 68 /// This form of SimplifyDemandedBits simplifies the specified instruction 69 /// operand if possible, updating it in place. It returns true if it made any 70 /// change and false otherwise. 71 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo, 72 const APInt &DemandedMask, 73 KnownBits &Known, unsigned Depth) { 74 Use &U = I->getOperandUse(OpNo); 75 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known, 76 Depth, I); 77 if (!NewVal) return false; 78 if (Instruction* OpInst = dyn_cast<Instruction>(U)) 79 salvageDebugInfo(*OpInst); 80 81 replaceUse(U, NewVal); 82 return true; 83 } 84 85 /// This function attempts to replace V with a simpler value based on the 86 /// demanded bits. When this function is called, it is known that only the bits 87 /// set in DemandedMask of the result of V are ever used downstream. 88 /// Consequently, depending on the mask and V, it may be possible to replace V 89 /// with a constant or one of its operands. In such cases, this function does 90 /// the replacement and returns true. In all other cases, it returns false after 91 /// analyzing the expression and setting KnownOne and known to be one in the 92 /// expression. Known.Zero contains all the bits that are known to be zero in 93 /// the expression. These are provided to potentially allow the caller (which 94 /// might recursively be SimplifyDemandedBits itself) to simplify the 95 /// expression. 96 /// Known.One and Known.Zero always follow the invariant that: 97 /// Known.One & Known.Zero == 0. 98 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and 99 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note 100 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all 101 /// be the same. 102 /// 103 /// This returns null if it did not change anything and it permits no 104 /// simplification. This returns V itself if it did some simplification of V's 105 /// operands based on the information about what bits are demanded. This returns 106 /// some other non-null value if it found out that V is equal to another value 107 /// in the context where the specified bits are demanded, but not for all users. 108 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 109 KnownBits &Known, 110 unsigned Depth, 111 Instruction *CxtI) { 112 assert(V != nullptr && "Null pointer of Value???"); 113 assert(Depth <= 6 && "Limit Search Depth"); 114 uint32_t BitWidth = DemandedMask.getBitWidth(); 115 Type *VTy = V->getType(); 116 assert( 117 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) && 118 Known.getBitWidth() == BitWidth && 119 "Value *V, DemandedMask and Known must have same BitWidth"); 120 121 if (isa<Constant>(V)) { 122 computeKnownBits(V, Known, Depth, CxtI); 123 return nullptr; 124 } 125 126 Known.resetAll(); 127 if (DemandedMask.isNullValue()) // Not demanding any bits from V. 128 return UndefValue::get(VTy); 129 130 if (Depth == 6) // Limit search depth. 131 return nullptr; 132 133 Instruction *I = dyn_cast<Instruction>(V); 134 if (!I) { 135 computeKnownBits(V, Known, Depth, CxtI); 136 return nullptr; // Only analyze instructions. 137 } 138 139 // If there are multiple uses of this value and we aren't at the root, then 140 // we can't do any simplifications of the operands, because DemandedMask 141 // only reflects the bits demanded by *one* of the users. 142 if (Depth != 0 && !I->hasOneUse()) 143 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI); 144 145 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth); 146 147 // If this is the root being simplified, allow it to have multiple uses, 148 // just set the DemandedMask to all bits so that we can try to simplify the 149 // operands. This allows visitTruncInst (for example) to simplify the 150 // operand of a trunc without duplicating all the logic below. 151 if (Depth == 0 && !V->hasOneUse()) 152 DemandedMask.setAllBits(); 153 154 switch (I->getOpcode()) { 155 default: 156 computeKnownBits(I, Known, Depth, CxtI); 157 break; 158 case Instruction::And: { 159 // If either the LHS or the RHS are Zero, the result is zero. 160 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 161 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, 162 Depth + 1)) 163 return I; 164 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 165 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 166 167 Known = LHSKnown & RHSKnown; 168 169 // If the client is only demanding bits that we know, return the known 170 // constant. 171 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 172 return Constant::getIntegerValue(VTy, Known.One); 173 174 // If all of the demanded bits are known 1 on one side, return the other. 175 // These bits cannot contribute to the result of the 'and'. 176 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 177 return I->getOperand(0); 178 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 179 return I->getOperand(1); 180 181 // If the RHS is a constant, see if we can simplify it. 182 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero)) 183 return I; 184 185 break; 186 } 187 case Instruction::Or: { 188 // If either the LHS or the RHS are One, the result is One. 189 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 190 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, 191 Depth + 1)) 192 return I; 193 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 194 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 195 196 Known = LHSKnown | RHSKnown; 197 198 // If the client is only demanding bits that we know, return the known 199 // constant. 200 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 201 return Constant::getIntegerValue(VTy, Known.One); 202 203 // If all of the demanded bits are known zero on one side, return the other. 204 // These bits cannot contribute to the result of the 'or'. 205 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 206 return I->getOperand(0); 207 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 208 return I->getOperand(1); 209 210 // If the RHS is a constant, see if we can simplify it. 211 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 212 return I; 213 214 break; 215 } 216 case Instruction::Xor: { 217 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 218 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1)) 219 return I; 220 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 221 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 222 223 Known = LHSKnown ^ RHSKnown; 224 225 // If the client is only demanding bits that we know, return the known 226 // constant. 227 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 228 return Constant::getIntegerValue(VTy, Known.One); 229 230 // If all of the demanded bits are known zero on one side, return the other. 231 // These bits cannot contribute to the result of the 'xor'. 232 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 233 return I->getOperand(0); 234 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 235 return I->getOperand(1); 236 237 // If all of the demanded bits are known to be zero on one side or the 238 // other, turn this into an *inclusive* or. 239 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 240 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) { 241 Instruction *Or = 242 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1), 243 I->getName()); 244 return InsertNewInstWith(Or, *I); 245 } 246 247 // If all of the demanded bits on one side are known, and all of the set 248 // bits on that side are also known to be set on the other side, turn this 249 // into an AND, as we know the bits will be cleared. 250 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 251 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) && 252 RHSKnown.One.isSubsetOf(LHSKnown.One)) { 253 Constant *AndC = Constant::getIntegerValue(VTy, 254 ~RHSKnown.One & DemandedMask); 255 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 256 return InsertNewInstWith(And, *I); 257 } 258 259 // If the RHS is a constant, see if we can simplify it. 260 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1. 261 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 262 return I; 263 264 // If our LHS is an 'and' and if it has one use, and if any of the bits we 265 // are flipping are known to be set, then the xor is just resetting those 266 // bits to zero. We can just knock out bits from the 'and' and the 'xor', 267 // simplifying both of them. 268 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) 269 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() && 270 isa<ConstantInt>(I->getOperand(1)) && 271 isa<ConstantInt>(LHSInst->getOperand(1)) && 272 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) { 273 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1)); 274 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1)); 275 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask); 276 277 Constant *AndC = 278 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue()); 279 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 280 InsertNewInstWith(NewAnd, *I); 281 282 Constant *XorC = 283 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue()); 284 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC); 285 return InsertNewInstWith(NewXor, *I); 286 } 287 288 break; 289 } 290 case Instruction::Select: { 291 Value *LHS, *RHS; 292 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor; 293 if (SPF == SPF_UMAX) { 294 // UMax(A, C) == A if ... 295 // The lowest non-zero bit of DemandMask is higher than the highest 296 // non-zero bit of C. 297 const APInt *C; 298 unsigned CTZ = DemandedMask.countTrailingZeros(); 299 if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits()) 300 return LHS; 301 } else if (SPF == SPF_UMIN) { 302 // UMin(A, C) == A if ... 303 // The lowest non-zero bit of DemandMask is higher than the highest 304 // non-one bit of C. 305 // This comes from using DeMorgans on the above umax example. 306 const APInt *C; 307 unsigned CTZ = DemandedMask.countTrailingZeros(); 308 if (match(RHS, m_APInt(C)) && 309 CTZ >= C->getBitWidth() - C->countLeadingOnes()) 310 return LHS; 311 } 312 313 // If this is a select as part of any other min/max pattern, don't simplify 314 // any further in case we break the structure. 315 if (SPF != SPF_UNKNOWN) 316 return nullptr; 317 318 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) || 319 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1)) 320 return I; 321 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 322 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 323 324 // If the operands are constants, see if we can simplify them. 325 // This is similar to ShrinkDemandedConstant, but for a select we want to 326 // try to keep the selected constants the same as icmp value constants, if 327 // we can. This helps not break apart (or helps put back together) 328 // canonical patterns like min and max. 329 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo, 330 APInt DemandedMask) { 331 const APInt *SelC; 332 if (!match(I->getOperand(OpNo), m_APInt(SelC))) 333 return false; 334 335 // Get the constant out of the ICmp, if there is one. 336 const APInt *CmpC; 337 ICmpInst::Predicate Pred; 338 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_APInt(CmpC), m_Value())) || 339 CmpC->getBitWidth() != SelC->getBitWidth()) 340 return ShrinkDemandedConstant(I, OpNo, DemandedMask); 341 342 // If the constant is already the same as the ICmp, leave it as-is. 343 if (*CmpC == *SelC) 344 return false; 345 // If the constants are not already the same, but can be with the demand 346 // mask, use the constant value from the ICmp. 347 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) { 348 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC)); 349 return true; 350 } 351 return ShrinkDemandedConstant(I, OpNo, DemandedMask); 352 }; 353 if (CanonicalizeSelectConstant(I, 1, DemandedMask) || 354 CanonicalizeSelectConstant(I, 2, DemandedMask)) 355 return I; 356 357 // Only known if known in both the LHS and RHS. 358 Known.One = RHSKnown.One & LHSKnown.One; 359 Known.Zero = RHSKnown.Zero & LHSKnown.Zero; 360 break; 361 } 362 case Instruction::ZExt: 363 case Instruction::Trunc: { 364 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 365 366 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth); 367 KnownBits InputKnown(SrcBitWidth); 368 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1)) 369 return I; 370 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?"); 371 Known = InputKnown.zextOrTrunc(BitWidth); 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 if ((DemandedMask & 1) == 0) { 428 // If we do not need the low bit, try to convert bool math to logic: 429 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN 430 Value *X, *Y; 431 if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))), 432 m_OneUse(m_SExt(m_Value(Y))))) && 433 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) { 434 // Truth table for inputs and output signbits: 435 // X:0 | X:1 436 // ---------- 437 // Y:0 | 0 | 0 | 438 // Y:1 | -1 | 0 | 439 // ---------- 440 IRBuilderBase::InsertPointGuard Guard(Builder); 441 Builder.SetInsertPoint(I); 442 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y); 443 return Builder.CreateSExt(AndNot, VTy); 444 } 445 446 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN 447 // TODO: Relax the one-use checks because we are removing an instruction? 448 if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))), 449 m_OneUse(m_SExt(m_Value(Y))))) && 450 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) { 451 // Truth table for inputs and output signbits: 452 // X:0 | X:1 453 // ----------- 454 // Y:0 | -1 | -1 | 455 // Y:1 | -1 | 0 | 456 // ----------- 457 IRBuilderBase::InsertPointGuard Guard(Builder); 458 Builder.SetInsertPoint(I); 459 Value *Or = Builder.CreateOr(X, Y); 460 return Builder.CreateSExt(Or, VTy); 461 } 462 } 463 LLVM_FALLTHROUGH; 464 case Instruction::Sub: { 465 /// If the high-bits of an ADD/SUB are not demanded, then we do not care 466 /// about the high bits of the operands. 467 unsigned NLZ = DemandedMask.countLeadingZeros(); 468 // Right fill the mask of bits for this ADD/SUB to demand the most 469 // significant bit and all those below it. 470 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ)); 471 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) || 472 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) || 473 ShrinkDemandedConstant(I, 1, DemandedFromOps) || 474 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) { 475 if (NLZ > 0) { 476 // Disable the nsw and nuw flags here: We can no longer guarantee that 477 // we won't wrap after simplification. Removing the nsw/nuw flags is 478 // legal here because the top bit is not demanded. 479 BinaryOperator &BinOP = *cast<BinaryOperator>(I); 480 BinOP.setHasNoSignedWrap(false); 481 BinOP.setHasNoUnsignedWrap(false); 482 } 483 return I; 484 } 485 486 // If we are known to be adding/subtracting zeros to every bit below 487 // the highest demanded bit, we just return the other side. 488 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero)) 489 return I->getOperand(0); 490 // We can't do this with the LHS for subtraction, unless we are only 491 // demanding the LSB. 492 if ((I->getOpcode() == Instruction::Add || 493 DemandedFromOps.isOneValue()) && 494 DemandedFromOps.isSubsetOf(LHSKnown.Zero)) 495 return I->getOperand(1); 496 497 // Otherwise just compute the known bits of the result. 498 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 499 Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add, 500 NSW, LHSKnown, RHSKnown); 501 break; 502 } 503 case Instruction::Shl: { 504 const APInt *SA; 505 if (match(I->getOperand(1), m_APInt(SA))) { 506 const APInt *ShrAmt; 507 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt)))) 508 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0))) 509 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA, 510 DemandedMask, Known)) 511 return R; 512 513 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 514 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt)); 515 516 // If the shift is NUW/NSW, then it does demand the high bits. 517 ShlOperator *IOp = cast<ShlOperator>(I); 518 if (IOp->hasNoSignedWrap()) 519 DemandedMaskIn.setHighBits(ShiftAmt+1); 520 else if (IOp->hasNoUnsignedWrap()) 521 DemandedMaskIn.setHighBits(ShiftAmt); 522 523 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 524 return I; 525 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 526 527 bool SignBitZero = Known.Zero.isSignBitSet(); 528 bool SignBitOne = Known.One.isSignBitSet(); 529 Known.Zero <<= ShiftAmt; 530 Known.One <<= ShiftAmt; 531 // low bits known zero. 532 if (ShiftAmt) 533 Known.Zero.setLowBits(ShiftAmt); 534 535 // If this shift has "nsw" keyword, then the result is either a poison 536 // value or has the same sign bit as the first operand. 537 if (IOp->hasNoSignedWrap()) { 538 if (SignBitZero) 539 Known.Zero.setSignBit(); 540 else if (SignBitOne) 541 Known.One.setSignBit(); 542 if (Known.hasConflict()) 543 return UndefValue::get(I->getType()); 544 } 545 } else { 546 computeKnownBits(I, Known, Depth, CxtI); 547 } 548 break; 549 } 550 case Instruction::LShr: { 551 const APInt *SA; 552 if (match(I->getOperand(1), m_APInt(SA))) { 553 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 554 555 // Unsigned shift right. 556 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 557 558 // If the shift is exact, then it does demand the low bits (and knows that 559 // they are zero). 560 if (cast<LShrOperator>(I)->isExact()) 561 DemandedMaskIn.setLowBits(ShiftAmt); 562 563 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 564 return I; 565 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 566 Known.Zero.lshrInPlace(ShiftAmt); 567 Known.One.lshrInPlace(ShiftAmt); 568 if (ShiftAmt) 569 Known.Zero.setHighBits(ShiftAmt); // high bits known zero. 570 } else { 571 computeKnownBits(I, Known, Depth, CxtI); 572 } 573 break; 574 } 575 case Instruction::AShr: { 576 // If this is an arithmetic shift right and only the low-bit is set, we can 577 // always convert this into a logical shr, even if the shift amount is 578 // variable. The low bit of the shift cannot be an input sign bit unless 579 // the shift amount is >= the size of the datatype, which is undefined. 580 if (DemandedMask.isOneValue()) { 581 // Perform the logical shift right. 582 Instruction *NewVal = BinaryOperator::CreateLShr( 583 I->getOperand(0), I->getOperand(1), I->getName()); 584 return InsertNewInstWith(NewVal, *I); 585 } 586 587 // If the sign bit is the only bit demanded by this ashr, then there is no 588 // need to do it, the shift doesn't change the high bit. 589 if (DemandedMask.isSignMask()) 590 return I->getOperand(0); 591 592 const APInt *SA; 593 if (match(I->getOperand(1), m_APInt(SA))) { 594 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 595 596 // Signed shift right. 597 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 598 // If any of the high bits are demanded, we should set the sign bit as 599 // demanded. 600 if (DemandedMask.countLeadingZeros() <= ShiftAmt) 601 DemandedMaskIn.setSignBit(); 602 603 // If the shift is exact, then it does demand the low bits (and knows that 604 // they are zero). 605 if (cast<AShrOperator>(I)->isExact()) 606 DemandedMaskIn.setLowBits(ShiftAmt); 607 608 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 609 return I; 610 611 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI); 612 613 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 614 // Compute the new bits that are at the top now plus sign bits. 615 APInt HighBits(APInt::getHighBitsSet( 616 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth))); 617 Known.Zero.lshrInPlace(ShiftAmt); 618 Known.One.lshrInPlace(ShiftAmt); 619 620 // If the input sign bit is known to be zero, or if none of the top bits 621 // are demanded, turn this into an unsigned shift right. 622 assert(BitWidth > ShiftAmt && "Shift amount not saturated?"); 623 if (Known.Zero[BitWidth-ShiftAmt-1] || 624 !DemandedMask.intersects(HighBits)) { 625 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0), 626 I->getOperand(1)); 627 LShr->setIsExact(cast<BinaryOperator>(I)->isExact()); 628 return InsertNewInstWith(LShr, *I); 629 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one. 630 Known.One |= HighBits; 631 } 632 } else { 633 computeKnownBits(I, Known, Depth, CxtI); 634 } 635 break; 636 } 637 case Instruction::UDiv: { 638 // UDiv doesn't demand low bits that are zero in the divisor. 639 const APInt *SA; 640 if (match(I->getOperand(1), m_APInt(SA))) { 641 // If the shift is exact, then it does demand the low bits. 642 if (cast<UDivOperator>(I)->isExact()) 643 break; 644 645 // FIXME: Take the demanded mask of the result into account. 646 unsigned RHSTrailingZeros = SA->countTrailingZeros(); 647 APInt DemandedMaskIn = 648 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros); 649 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) 650 return I; 651 652 // Propagate zero bits from the input. 653 Known.Zero.setHighBits(std::min( 654 BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros)); 655 } else { 656 computeKnownBits(I, Known, Depth, CxtI); 657 } 658 break; 659 } 660 case Instruction::SRem: 661 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 662 // X % -1 demands all the bits because we don't want to introduce 663 // INT_MIN % -1 (== undef) by accident. 664 if (Rem->isMinusOne()) 665 break; 666 APInt RA = Rem->getValue().abs(); 667 if (RA.isPowerOf2()) { 668 if (DemandedMask.ult(RA)) // srem won't affect demanded bits 669 return I->getOperand(0); 670 671 APInt LowBits = RA - 1; 672 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth); 673 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1)) 674 return I; 675 676 // The low bits of LHS are unchanged by the srem. 677 Known.Zero = LHSKnown.Zero & LowBits; 678 Known.One = LHSKnown.One & LowBits; 679 680 // If LHS is non-negative or has all low bits zero, then the upper bits 681 // are all zero. 682 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero)) 683 Known.Zero |= ~LowBits; 684 685 // If LHS is negative and not all low bits are zero, then the upper bits 686 // are all one. 687 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One)) 688 Known.One |= ~LowBits; 689 690 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 691 break; 692 } 693 } 694 695 // The sign bit is the LHS's sign bit, except when the result of the 696 // remainder is zero. 697 if (DemandedMask.isSignBitSet()) { 698 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI); 699 // If it's known zero, our sign bit is also zero. 700 if (LHSKnown.isNonNegative()) 701 Known.makeNonNegative(); 702 } 703 break; 704 case Instruction::URem: { 705 KnownBits Known2(BitWidth); 706 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 707 if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) || 708 SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1)) 709 return I; 710 711 unsigned Leaders = Known2.countMinLeadingZeros(); 712 Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask; 713 break; 714 } 715 case Instruction::Call: { 716 bool KnownBitsComputed = false; 717 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 718 switch (II->getIntrinsicID()) { 719 case Intrinsic::bswap: { 720 // If the only bits demanded come from one byte of the bswap result, 721 // just shift the input byte into position to eliminate the bswap. 722 unsigned NLZ = DemandedMask.countLeadingZeros(); 723 unsigned NTZ = DemandedMask.countTrailingZeros(); 724 725 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 726 // we need all the bits down to bit 8. Likewise, round NLZ. If we 727 // have 14 leading zeros, round to 8. 728 NLZ &= ~7; 729 NTZ &= ~7; 730 // If we need exactly one byte, we can do this transformation. 731 if (BitWidth-NLZ-NTZ == 8) { 732 unsigned ResultBit = NTZ; 733 unsigned InputBit = BitWidth-NTZ-8; 734 735 // Replace this with either a left or right shift to get the byte into 736 // the right place. 737 Instruction *NewVal; 738 if (InputBit > ResultBit) 739 NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0), 740 ConstantInt::get(I->getType(), InputBit-ResultBit)); 741 else 742 NewVal = BinaryOperator::CreateShl(II->getArgOperand(0), 743 ConstantInt::get(I->getType(), ResultBit-InputBit)); 744 NewVal->takeName(I); 745 return InsertNewInstWith(NewVal, *I); 746 } 747 break; 748 } 749 case Intrinsic::fshr: 750 case Intrinsic::fshl: { 751 const APInt *SA; 752 if (!match(I->getOperand(2), m_APInt(SA))) 753 break; 754 755 // Normalize to funnel shift left. APInt shifts of BitWidth are well- 756 // defined, so no need to special-case zero shifts here. 757 uint64_t ShiftAmt = SA->urem(BitWidth); 758 if (II->getIntrinsicID() == Intrinsic::fshr) 759 ShiftAmt = BitWidth - ShiftAmt; 760 761 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt)); 762 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt)); 763 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) || 764 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1)) 765 return I; 766 767 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) | 768 RHSKnown.Zero.lshr(BitWidth - ShiftAmt); 769 Known.One = LHSKnown.One.shl(ShiftAmt) | 770 RHSKnown.One.lshr(BitWidth - ShiftAmt); 771 KnownBitsComputed = true; 772 break; 773 } 774 default: { 775 // Handle target specific intrinsics 776 Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic( 777 *II, DemandedMask, Known, KnownBitsComputed); 778 if (V.hasValue()) 779 return V.getValue(); 780 break; 781 } 782 } 783 } 784 785 if (!KnownBitsComputed) 786 computeKnownBits(V, Known, Depth, CxtI); 787 break; 788 } 789 } 790 791 // If the client is only demanding bits that we know, return the known 792 // constant. 793 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 794 return Constant::getIntegerValue(VTy, Known.One); 795 return nullptr; 796 } 797 798 /// Helper routine of SimplifyDemandedUseBits. It computes Known 799 /// bits. It also tries to handle simplifications that can be done based on 800 /// DemandedMask, but without modifying the Instruction. 801 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits( 802 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, 803 Instruction *CxtI) { 804 unsigned BitWidth = DemandedMask.getBitWidth(); 805 Type *ITy = I->getType(); 806 807 KnownBits LHSKnown(BitWidth); 808 KnownBits RHSKnown(BitWidth); 809 810 // Despite the fact that we can't simplify this instruction in all User's 811 // context, we can at least compute the known bits, and we can 812 // do simplifications that apply to *just* the one user if we know that 813 // this instruction has a simpler value in that context. 814 switch (I->getOpcode()) { 815 case Instruction::And: { 816 // If either the LHS or the RHS are Zero, the result is zero. 817 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 818 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 819 CxtI); 820 821 Known = LHSKnown & RHSKnown; 822 823 // If the client is only demanding bits that we know, return the known 824 // constant. 825 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 826 return Constant::getIntegerValue(ITy, Known.One); 827 828 // If all of the demanded bits are known 1 on one side, return the other. 829 // These bits cannot contribute to the result of the 'and' in this 830 // context. 831 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 832 return I->getOperand(0); 833 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 834 return I->getOperand(1); 835 836 break; 837 } 838 case Instruction::Or: { 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 // If either the LHS or the RHS are One, the result is One. 843 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 844 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 845 CxtI); 846 847 Known = LHSKnown | RHSKnown; 848 849 // If the client is only demanding bits that we know, return the known 850 // constant. 851 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 852 return Constant::getIntegerValue(ITy, Known.One); 853 854 // If all of the demanded bits are known zero on one side, return the 855 // other. These bits cannot contribute to the result of the 'or' in this 856 // context. 857 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 858 return I->getOperand(0); 859 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 860 return I->getOperand(1); 861 862 break; 863 } 864 case Instruction::Xor: { 865 // We can simplify (X^Y) -> X or Y in the user's context if we know that 866 // only bits from X or Y are demanded. 867 868 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 869 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 870 CxtI); 871 872 Known = LHSKnown ^ RHSKnown; 873 874 // If the client is only demanding bits that we know, return the known 875 // constant. 876 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 877 return Constant::getIntegerValue(ITy, Known.One); 878 879 // If all of the demanded bits are known zero on one side, return the 880 // other. 881 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 882 return I->getOperand(0); 883 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 884 return I->getOperand(1); 885 886 break; 887 } 888 default: 889 // Compute the Known bits to simplify things downstream. 890 computeKnownBits(I, Known, Depth, CxtI); 891 892 // If this user is only demanding bits that we know, return the known 893 // constant. 894 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 895 return Constant::getIntegerValue(ITy, Known.One); 896 897 break; 898 } 899 900 return nullptr; 901 } 902 903 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify 904 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into 905 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign 906 /// of "C2-C1". 907 /// 908 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1, 909 /// ..., bn}, without considering the specific value X is holding. 910 /// This transformation is legal iff one of following conditions is hold: 911 /// 1) All the bit in S are 0, in this case E1 == E2. 912 /// 2) We don't care those bits in S, per the input DemandedMask. 913 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the 914 /// rest bits. 915 /// 916 /// Currently we only test condition 2). 917 /// 918 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was 919 /// not successful. 920 Value *InstCombinerImpl::simplifyShrShlDemandedBits( 921 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, 922 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) { 923 if (!ShlOp1 || !ShrOp1) 924 return nullptr; // No-op. 925 926 Value *VarX = Shr->getOperand(0); 927 Type *Ty = VarX->getType(); 928 unsigned BitWidth = Ty->getScalarSizeInBits(); 929 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth)) 930 return nullptr; // Undef. 931 932 unsigned ShlAmt = ShlOp1.getZExtValue(); 933 unsigned ShrAmt = ShrOp1.getZExtValue(); 934 935 Known.One.clearAllBits(); 936 Known.Zero.setLowBits(ShlAmt - 1); 937 Known.Zero &= DemandedMask; 938 939 APInt BitMask1(APInt::getAllOnesValue(BitWidth)); 940 APInt BitMask2(APInt::getAllOnesValue(BitWidth)); 941 942 bool isLshr = (Shr->getOpcode() == Instruction::LShr); 943 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) : 944 (BitMask1.ashr(ShrAmt) << ShlAmt); 945 946 if (ShrAmt <= ShlAmt) { 947 BitMask2 <<= (ShlAmt - ShrAmt); 948 } else { 949 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt): 950 BitMask2.ashr(ShrAmt - ShlAmt); 951 } 952 953 // Check if condition-2 (see the comment to this function) is satified. 954 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) { 955 if (ShrAmt == ShlAmt) 956 return VarX; 957 958 if (!Shr->hasOneUse()) 959 return nullptr; 960 961 BinaryOperator *New; 962 if (ShrAmt < ShlAmt) { 963 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt); 964 New = BinaryOperator::CreateShl(VarX, Amt); 965 BinaryOperator *Orig = cast<BinaryOperator>(Shl); 966 New->setHasNoSignedWrap(Orig->hasNoSignedWrap()); 967 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap()); 968 } else { 969 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt); 970 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) : 971 BinaryOperator::CreateAShr(VarX, Amt); 972 if (cast<BinaryOperator>(Shr)->isExact()) 973 New->setIsExact(true); 974 } 975 976 return InsertNewInstWith(New, *Shl); 977 } 978 979 return nullptr; 980 } 981 982 /// The specified value produces a vector with any number of elements. 983 /// This method analyzes which elements of the operand are undef and returns 984 /// that information in UndefElts. 985 /// 986 /// DemandedElts contains the set of elements that are actually used by the 987 /// caller, and by default (AllowMultipleUsers equals false) the value is 988 /// simplified only if it has a single caller. If AllowMultipleUsers is set 989 /// to true, DemandedElts refers to the union of sets of elements that are 990 /// used by all callers. 991 /// 992 /// If the information about demanded elements can be used to simplify the 993 /// operation, the operation is simplified, then the resultant value is 994 /// returned. This returns null if no change was made. 995 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V, 996 APInt DemandedElts, 997 APInt &UndefElts, 998 unsigned Depth, 999 bool AllowMultipleUsers) { 1000 // Cannot analyze scalable type. The number of vector elements is not a 1001 // compile-time constant. 1002 if (isa<ScalableVectorType>(V->getType())) 1003 return nullptr; 1004 1005 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements(); 1006 APInt EltMask(APInt::getAllOnesValue(VWidth)); 1007 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!"); 1008 1009 if (isa<UndefValue>(V)) { 1010 // If the entire vector is undefined, just return this info. 1011 UndefElts = EltMask; 1012 return nullptr; 1013 } 1014 1015 if (DemandedElts.isNullValue()) { // If nothing is demanded, provide undef. 1016 UndefElts = EltMask; 1017 return UndefValue::get(V->getType()); 1018 } 1019 1020 UndefElts = 0; 1021 1022 if (auto *C = dyn_cast<Constant>(V)) { 1023 // Check if this is identity. If so, return 0 since we are not simplifying 1024 // anything. 1025 if (DemandedElts.isAllOnesValue()) 1026 return nullptr; 1027 1028 Type *EltTy = cast<VectorType>(V->getType())->getElementType(); 1029 Constant *Undef = UndefValue::get(EltTy); 1030 SmallVector<Constant*, 16> Elts; 1031 for (unsigned i = 0; i != VWidth; ++i) { 1032 if (!DemandedElts[i]) { // If not demanded, set to undef. 1033 Elts.push_back(Undef); 1034 UndefElts.setBit(i); 1035 continue; 1036 } 1037 1038 Constant *Elt = C->getAggregateElement(i); 1039 if (!Elt) return nullptr; 1040 1041 if (isa<UndefValue>(Elt)) { // Already undef. 1042 Elts.push_back(Undef); 1043 UndefElts.setBit(i); 1044 } else { // Otherwise, defined. 1045 Elts.push_back(Elt); 1046 } 1047 } 1048 1049 // If we changed the constant, return it. 1050 Constant *NewCV = ConstantVector::get(Elts); 1051 return NewCV != C ? NewCV : nullptr; 1052 } 1053 1054 // Limit search depth. 1055 if (Depth == 10) 1056 return nullptr; 1057 1058 if (!AllowMultipleUsers) { 1059 // If multiple users are using the root value, proceed with 1060 // simplification conservatively assuming that all elements 1061 // are needed. 1062 if (!V->hasOneUse()) { 1063 // Quit if we find multiple users of a non-root value though. 1064 // They'll be handled when it's their turn to be visited by 1065 // the main instcombine process. 1066 if (Depth != 0) 1067 // TODO: Just compute the UndefElts information recursively. 1068 return nullptr; 1069 1070 // Conservatively assume that all elements are needed. 1071 DemandedElts = EltMask; 1072 } 1073 } 1074 1075 Instruction *I = dyn_cast<Instruction>(V); 1076 if (!I) return nullptr; // Only analyze instructions. 1077 1078 bool MadeChange = false; 1079 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum, 1080 APInt Demanded, APInt &Undef) { 1081 auto *II = dyn_cast<IntrinsicInst>(Inst); 1082 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum); 1083 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) { 1084 replaceOperand(*Inst, OpNum, V); 1085 MadeChange = true; 1086 } 1087 }; 1088 1089 APInt UndefElts2(VWidth, 0); 1090 APInt UndefElts3(VWidth, 0); 1091 switch (I->getOpcode()) { 1092 default: break; 1093 1094 case Instruction::GetElementPtr: { 1095 // The LangRef requires that struct geps have all constant indices. As 1096 // such, we can't convert any operand to partial undef. 1097 auto mayIndexStructType = [](GetElementPtrInst &GEP) { 1098 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP); 1099 I != E; I++) 1100 if (I.isStruct()) 1101 return true;; 1102 return false; 1103 }; 1104 if (mayIndexStructType(cast<GetElementPtrInst>(*I))) 1105 break; 1106 1107 // Conservatively track the demanded elements back through any vector 1108 // operands we may have. We know there must be at least one, or we 1109 // wouldn't have a vector result to get here. Note that we intentionally 1110 // merge the undef bits here since gepping with either an undef base or 1111 // index results in undef. 1112 for (unsigned i = 0; i < I->getNumOperands(); i++) { 1113 if (isa<UndefValue>(I->getOperand(i))) { 1114 // If the entire vector is undefined, just return this info. 1115 UndefElts = EltMask; 1116 return nullptr; 1117 } 1118 if (I->getOperand(i)->getType()->isVectorTy()) { 1119 APInt UndefEltsOp(VWidth, 0); 1120 simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp); 1121 UndefElts |= UndefEltsOp; 1122 } 1123 } 1124 1125 break; 1126 } 1127 case Instruction::InsertElement: { 1128 // If this is a variable index, we don't know which element it overwrites. 1129 // demand exactly the same input as we produce. 1130 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2)); 1131 if (!Idx) { 1132 // Note that we can't propagate undef elt info, because we don't know 1133 // which elt is getting updated. 1134 simplifyAndSetOp(I, 0, DemandedElts, UndefElts2); 1135 break; 1136 } 1137 1138 // The element inserted overwrites whatever was there, so the input demanded 1139 // set is simpler than the output set. 1140 unsigned IdxNo = Idx->getZExtValue(); 1141 APInt PreInsertDemandedElts = DemandedElts; 1142 if (IdxNo < VWidth) 1143 PreInsertDemandedElts.clearBit(IdxNo); 1144 1145 simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts); 1146 1147 // If this is inserting an element that isn't demanded, remove this 1148 // insertelement. 1149 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) { 1150 Worklist.push(I); 1151 return I->getOperand(0); 1152 } 1153 1154 // The inserted element is defined. 1155 UndefElts.clearBit(IdxNo); 1156 break; 1157 } 1158 case Instruction::ShuffleVector: { 1159 auto *Shuffle = cast<ShuffleVectorInst>(I); 1160 assert(Shuffle->getOperand(0)->getType() == 1161 Shuffle->getOperand(1)->getType() && 1162 "Expected shuffle operands to have same type"); 1163 unsigned OpWidth = 1164 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements(); 1165 // Handle trivial case of a splat. Only check the first element of LHS 1166 // operand. 1167 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) && 1168 DemandedElts.isAllOnesValue()) { 1169 if (!isa<UndefValue>(I->getOperand(1))) { 1170 I->setOperand(1, UndefValue::get(I->getOperand(1)->getType())); 1171 MadeChange = true; 1172 } 1173 APInt LeftDemanded(OpWidth, 1); 1174 APInt LHSUndefElts(OpWidth, 0); 1175 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts); 1176 if (LHSUndefElts[0]) 1177 UndefElts = EltMask; 1178 else 1179 UndefElts.clearAllBits(); 1180 break; 1181 } 1182 1183 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0); 1184 for (unsigned i = 0; i < VWidth; i++) { 1185 if (DemandedElts[i]) { 1186 unsigned MaskVal = Shuffle->getMaskValue(i); 1187 if (MaskVal != -1u) { 1188 assert(MaskVal < OpWidth * 2 && 1189 "shufflevector mask index out of range!"); 1190 if (MaskVal < OpWidth) 1191 LeftDemanded.setBit(MaskVal); 1192 else 1193 RightDemanded.setBit(MaskVal - OpWidth); 1194 } 1195 } 1196 } 1197 1198 APInt LHSUndefElts(OpWidth, 0); 1199 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts); 1200 1201 APInt RHSUndefElts(OpWidth, 0); 1202 simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts); 1203 1204 // If this shuffle does not change the vector length and the elements 1205 // demanded by this shuffle are an identity mask, then this shuffle is 1206 // unnecessary. 1207 // 1208 // We are assuming canonical form for the mask, so the source vector is 1209 // operand 0 and operand 1 is not used. 1210 // 1211 // Note that if an element is demanded and this shuffle mask is undefined 1212 // for that element, then the shuffle is not considered an identity 1213 // operation. The shuffle prevents poison from the operand vector from 1214 // leaking to the result by replacing poison with an undefined value. 1215 if (VWidth == OpWidth) { 1216 bool IsIdentityShuffle = true; 1217 for (unsigned i = 0; i < VWidth; i++) { 1218 unsigned MaskVal = Shuffle->getMaskValue(i); 1219 if (DemandedElts[i] && i != MaskVal) { 1220 IsIdentityShuffle = false; 1221 break; 1222 } 1223 } 1224 if (IsIdentityShuffle) 1225 return Shuffle->getOperand(0); 1226 } 1227 1228 bool NewUndefElts = false; 1229 unsigned LHSIdx = -1u, LHSValIdx = -1u; 1230 unsigned RHSIdx = -1u, RHSValIdx = -1u; 1231 bool LHSUniform = true; 1232 bool RHSUniform = true; 1233 for (unsigned i = 0; i < VWidth; i++) { 1234 unsigned MaskVal = Shuffle->getMaskValue(i); 1235 if (MaskVal == -1u) { 1236 UndefElts.setBit(i); 1237 } else if (!DemandedElts[i]) { 1238 NewUndefElts = true; 1239 UndefElts.setBit(i); 1240 } else if (MaskVal < OpWidth) { 1241 if (LHSUndefElts[MaskVal]) { 1242 NewUndefElts = true; 1243 UndefElts.setBit(i); 1244 } else { 1245 LHSIdx = LHSIdx == -1u ? i : OpWidth; 1246 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth; 1247 LHSUniform = LHSUniform && (MaskVal == i); 1248 } 1249 } else { 1250 if (RHSUndefElts[MaskVal - OpWidth]) { 1251 NewUndefElts = true; 1252 UndefElts.setBit(i); 1253 } else { 1254 RHSIdx = RHSIdx == -1u ? i : OpWidth; 1255 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth; 1256 RHSUniform = RHSUniform && (MaskVal - OpWidth == i); 1257 } 1258 } 1259 } 1260 1261 // Try to transform shuffle with constant vector and single element from 1262 // this constant vector to single insertelement instruction. 1263 // shufflevector V, C, <v1, v2, .., ci, .., vm> -> 1264 // insertelement V, C[ci], ci-n 1265 if (OpWidth == Shuffle->getType()->getNumElements()) { 1266 Value *Op = nullptr; 1267 Constant *Value = nullptr; 1268 unsigned Idx = -1u; 1269 1270 // Find constant vector with the single element in shuffle (LHS or RHS). 1271 if (LHSIdx < OpWidth && RHSUniform) { 1272 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) { 1273 Op = Shuffle->getOperand(1); 1274 Value = CV->getOperand(LHSValIdx); 1275 Idx = LHSIdx; 1276 } 1277 } 1278 if (RHSIdx < OpWidth && LHSUniform) { 1279 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) { 1280 Op = Shuffle->getOperand(0); 1281 Value = CV->getOperand(RHSValIdx); 1282 Idx = RHSIdx; 1283 } 1284 } 1285 // Found constant vector with single element - convert to insertelement. 1286 if (Op && Value) { 1287 Instruction *New = InsertElementInst::Create( 1288 Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx), 1289 Shuffle->getName()); 1290 InsertNewInstWith(New, *Shuffle); 1291 return New; 1292 } 1293 } 1294 if (NewUndefElts) { 1295 // Add additional discovered undefs. 1296 SmallVector<int, 16> Elts; 1297 for (unsigned i = 0; i < VWidth; ++i) { 1298 if (UndefElts[i]) 1299 Elts.push_back(UndefMaskElem); 1300 else 1301 Elts.push_back(Shuffle->getMaskValue(i)); 1302 } 1303 Shuffle->setShuffleMask(Elts); 1304 MadeChange = true; 1305 } 1306 break; 1307 } 1308 case Instruction::Select: { 1309 // If this is a vector select, try to transform the select condition based 1310 // on the current demanded elements. 1311 SelectInst *Sel = cast<SelectInst>(I); 1312 if (Sel->getCondition()->getType()->isVectorTy()) { 1313 // TODO: We are not doing anything with UndefElts based on this call. 1314 // It is overwritten below based on the other select operands. If an 1315 // element of the select condition is known undef, then we are free to 1316 // choose the output value from either arm of the select. If we know that 1317 // one of those values is undef, then the output can be undef. 1318 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1319 } 1320 1321 // Next, see if we can transform the arms of the select. 1322 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts); 1323 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) { 1324 for (unsigned i = 0; i < VWidth; i++) { 1325 // isNullValue() always returns false when called on a ConstantExpr. 1326 // Skip constant expressions to avoid propagating incorrect information. 1327 Constant *CElt = CV->getAggregateElement(i); 1328 if (isa<ConstantExpr>(CElt)) 1329 continue; 1330 // TODO: If a select condition element is undef, we can demand from 1331 // either side. If one side is known undef, choosing that side would 1332 // propagate undef. 1333 if (CElt->isNullValue()) 1334 DemandedLHS.clearBit(i); 1335 else 1336 DemandedRHS.clearBit(i); 1337 } 1338 } 1339 1340 simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2); 1341 simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3); 1342 1343 // Output elements are undefined if the element from each arm is undefined. 1344 // TODO: This can be improved. See comment in select condition handling. 1345 UndefElts = UndefElts2 & UndefElts3; 1346 break; 1347 } 1348 case Instruction::BitCast: { 1349 // Vector->vector casts only. 1350 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType()); 1351 if (!VTy) break; 1352 unsigned InVWidth = VTy->getNumElements(); 1353 APInt InputDemandedElts(InVWidth, 0); 1354 UndefElts2 = APInt(InVWidth, 0); 1355 unsigned Ratio; 1356 1357 if (VWidth == InVWidth) { 1358 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same 1359 // elements as are demanded of us. 1360 Ratio = 1; 1361 InputDemandedElts = DemandedElts; 1362 } else if ((VWidth % InVWidth) == 0) { 1363 // If the number of elements in the output is a multiple of the number of 1364 // elements in the input then an input element is live if any of the 1365 // corresponding output elements are live. 1366 Ratio = VWidth / InVWidth; 1367 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1368 if (DemandedElts[OutIdx]) 1369 InputDemandedElts.setBit(OutIdx / Ratio); 1370 } else if ((InVWidth % VWidth) == 0) { 1371 // If the number of elements in the input is a multiple of the number of 1372 // elements in the output then an input element is live if the 1373 // corresponding output element is live. 1374 Ratio = InVWidth / VWidth; 1375 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx) 1376 if (DemandedElts[InIdx / Ratio]) 1377 InputDemandedElts.setBit(InIdx); 1378 } else { 1379 // Unsupported so far. 1380 break; 1381 } 1382 1383 simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2); 1384 1385 if (VWidth == InVWidth) { 1386 UndefElts = UndefElts2; 1387 } else if ((VWidth % InVWidth) == 0) { 1388 // If the number of elements in the output is a multiple of the number of 1389 // elements in the input then an output element is undef if the 1390 // corresponding input element is undef. 1391 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1392 if (UndefElts2[OutIdx / Ratio]) 1393 UndefElts.setBit(OutIdx); 1394 } else if ((InVWidth % VWidth) == 0) { 1395 // If the number of elements in the input is a multiple of the number of 1396 // elements in the output then an output element is undef if all of the 1397 // corresponding input elements are undef. 1398 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) { 1399 APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio); 1400 if (SubUndef.countPopulation() == Ratio) 1401 UndefElts.setBit(OutIdx); 1402 } 1403 } else { 1404 llvm_unreachable("Unimp"); 1405 } 1406 break; 1407 } 1408 case Instruction::FPTrunc: 1409 case Instruction::FPExt: 1410 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1411 break; 1412 1413 case Instruction::Call: { 1414 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1415 if (!II) break; 1416 switch (II->getIntrinsicID()) { 1417 case Intrinsic::masked_gather: // fallthrough 1418 case Intrinsic::masked_load: { 1419 // Subtlety: If we load from a pointer, the pointer must be valid 1420 // regardless of whether the element is demanded. Doing otherwise risks 1421 // segfaults which didn't exist in the original program. 1422 APInt DemandedPtrs(APInt::getAllOnesValue(VWidth)), 1423 DemandedPassThrough(DemandedElts); 1424 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2))) 1425 for (unsigned i = 0; i < VWidth; i++) { 1426 Constant *CElt = CV->getAggregateElement(i); 1427 if (CElt->isNullValue()) 1428 DemandedPtrs.clearBit(i); 1429 else if (CElt->isAllOnesValue()) 1430 DemandedPassThrough.clearBit(i); 1431 } 1432 if (II->getIntrinsicID() == Intrinsic::masked_gather) 1433 simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2); 1434 simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3); 1435 1436 // Output elements are undefined if the element from both sources are. 1437 // TODO: can strengthen via mask as well. 1438 UndefElts = UndefElts2 & UndefElts3; 1439 break; 1440 } 1441 default: { 1442 // Handle target specific intrinsics 1443 Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic( 1444 *II, DemandedElts, UndefElts, UndefElts2, UndefElts3, 1445 simplifyAndSetOp); 1446 if (V.hasValue()) 1447 return V.getValue(); 1448 break; 1449 } 1450 } // switch on IntrinsicID 1451 break; 1452 } // case Call 1453 } // switch on Opcode 1454 1455 // TODO: We bail completely on integer div/rem and shifts because they have 1456 // UB/poison potential, but that should be refined. 1457 BinaryOperator *BO; 1458 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) { 1459 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1460 simplifyAndSetOp(I, 1, DemandedElts, UndefElts2); 1461 1462 // Any change to an instruction with potential poison must clear those flags 1463 // because we can not guarantee those constraints now. Other analysis may 1464 // determine that it is safe to re-apply the flags. 1465 if (MadeChange) 1466 BO->dropPoisonGeneratingFlags(); 1467 1468 // Output elements are undefined if both are undefined. Consider things 1469 // like undef & 0. The result is known zero, not undef. 1470 UndefElts &= UndefElts2; 1471 } 1472 1473 // If we've proven all of the lanes undef, return an undef value. 1474 // TODO: Intersect w/demanded lanes 1475 if (UndefElts.isAllOnesValue()) 1476 return UndefValue::get(I->getType());; 1477 1478 return MadeChange ? I : nullptr; 1479 } 1480