1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains logic for simplifying instructions based on information
11 // about how they are used.
13 //===----------------------------------------------------------------------===//
15 #include "InstCombineInternal.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
20 using namespace llvm::PatternMatch;
22 #define DEBUG_TYPE "instcombine"
24 /// ShrinkDemandedConstant - Check to see if the specified operand of the
25 /// specified instruction is a constant integer. If so, check to see if there
26 /// are any bits set in the constant that are not demanded. If so, shrink the
27 /// constant and return true.
28 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
30 assert(I && "No instruction?");
31 assert(OpNo < I->getNumOperands() && "Operand index too large");
33 // If the operand is not a constant integer, nothing to do.
34 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
35 if (!OpC) return false;
37 // If there are no bits set that aren't demanded, nothing to do.
38 Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
39 if ((~Demanded & OpC->getValue()) == 0)
42 // This instruction is producing bits that are not demanded. Shrink the RHS.
43 Demanded &= OpC->getValue();
44 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
46 // If either 'nsw' or 'nuw' is set and the constant is negative,
47 // removing *any* bits from the constant could make overflow occur.
48 // Remove 'nsw' and 'nuw' from the instruction in this case.
49 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
50 assert(OBO->getOpcode() == Instruction::Add);
51 if (OBO->hasNoSignedWrap() || OBO->hasNoUnsignedWrap()) {
52 if (OpC->getValue().isNegative()) {
53 cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
54 cast<BinaryOperator>(OBO)->setHasNoUnsignedWrap(false);
64 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
65 /// SimplifyDemandedBits knows about. See if the instruction has any
66 /// properties that allow us to simplify its operands.
67 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
68 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
69 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
70 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
72 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, KnownZero, KnownOne,
75 if (V == &Inst) return true;
76 ReplaceInstUsesWith(Inst, V);
80 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
81 /// specified instruction operand if possible, updating it in place. It returns
82 /// true if it made any change and false otherwise.
83 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
84 APInt &KnownZero, APInt &KnownOne,
86 auto *UserI = dyn_cast<Instruction>(U.getUser());
87 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, KnownZero,
88 KnownOne, Depth, UserI);
89 if (!NewVal) return false;
95 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
96 /// value based on the demanded bits. When this function is called, it is known
97 /// that only the bits set in DemandedMask of the result of V are ever used
98 /// downstream. Consequently, depending on the mask and V, it may be possible
99 /// to replace V with a constant or one of its operands. In such cases, this
100 /// function does the replacement and returns true. In all other cases, it
101 /// returns false after analyzing the expression and setting KnownOne and known
102 /// to be one in the expression. KnownZero contains all the bits that are known
103 /// to be zero in the expression. These are provided to potentially allow the
104 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
105 /// the expression. KnownOne and KnownZero always follow the invariant that
106 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
107 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
108 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
109 /// and KnownOne must all be the same.
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 APInt &KnownZero, APInt &KnownOne,
120 assert(V != nullptr && "Null pointer of Value???");
121 assert(Depth <= 6 && "Limit Search Depth");
122 uint32_t BitWidth = DemandedMask.getBitWidth();
123 Type *VTy = V->getType();
125 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
126 KnownZero.getBitWidth() == BitWidth &&
127 KnownOne.getBitWidth() == BitWidth &&
128 "Value *V, DemandedMask, KnownZero and KnownOne "
129 "must have same BitWidth");
130 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
131 // We know all of the bits for a constant!
132 KnownOne = CI->getValue() & DemandedMask;
133 KnownZero = ~KnownOne & DemandedMask;
136 if (isa<ConstantPointerNull>(V)) {
137 // We know all of the bits for a constant!
138 KnownOne.clearAllBits();
139 KnownZero = DemandedMask;
143 KnownZero.clearAllBits();
144 KnownOne.clearAllBits();
145 if (DemandedMask == 0) { // Not demanding any bits from V.
146 if (isa<UndefValue>(V))
148 return UndefValue::get(VTy);
151 if (Depth == 6) // Limit search depth.
154 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
155 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
157 Instruction *I = dyn_cast<Instruction>(V);
159 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
160 return nullptr; // Only analyze instructions.
163 // If there are multiple uses of this value and we aren't at the root, then
164 // we can't do any simplifications of the operands, because DemandedMask
165 // only reflects the bits demanded by *one* of the users.
166 if (Depth != 0 && !I->hasOneUse()) {
167 // Despite the fact that we can't simplify this instruction in all User's
168 // context, we can at least compute the knownzero/knownone bits, and we can
169 // do simplifications that apply to *just* the one user if we know that
170 // this instruction has a simpler value in that context.
171 if (I->getOpcode() == Instruction::And) {
172 // If either the LHS or the RHS are Zero, the result is zero.
173 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
175 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
178 // If all of the demanded bits are known 1 on one side, return the other.
179 // These bits cannot contribute to the result of the 'and' in this
181 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
182 (DemandedMask & ~LHSKnownZero))
183 return I->getOperand(0);
184 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
185 (DemandedMask & ~RHSKnownZero))
186 return I->getOperand(1);
188 // If all of the demanded bits in the inputs are known zeros, return zero.
189 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
190 return Constant::getNullValue(VTy);
192 } else if (I->getOpcode() == Instruction::Or) {
193 // We can simplify (X|Y) -> X or Y in the user's context if we know that
194 // only bits from X or Y are demanded.
196 // If either the LHS or the RHS are One, the result is One.
197 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
199 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
202 // If all of the demanded bits are known zero on one side, return the
203 // other. These bits cannot contribute to the result of the 'or' in this
205 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
206 (DemandedMask & ~LHSKnownOne))
207 return I->getOperand(0);
208 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
209 (DemandedMask & ~RHSKnownOne))
210 return I->getOperand(1);
212 // If all of the potentially set bits on one side are known to be set on
213 // the other side, just use the 'other' side.
214 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
215 (DemandedMask & (~RHSKnownZero)))
216 return I->getOperand(0);
217 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
218 (DemandedMask & (~LHSKnownZero)))
219 return I->getOperand(1);
220 } else if (I->getOpcode() == Instruction::Xor) {
221 // We can simplify (X^Y) -> X or Y in the user's context if we know that
222 // only bits from X or Y are demanded.
224 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
226 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
229 // If all of the demanded bits are known zero on one side, return the
231 if ((DemandedMask & RHSKnownZero) == DemandedMask)
232 return I->getOperand(0);
233 if ((DemandedMask & LHSKnownZero) == DemandedMask)
234 return I->getOperand(1);
237 // Compute the KnownZero/KnownOne bits to simplify things downstream.
238 computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
242 // If this is the root being simplified, allow it to have multiple uses,
243 // just set the DemandedMask to all bits so that we can try to simplify the
244 // operands. This allows visitTruncInst (for example) to simplify the
245 // operand of a trunc without duplicating all the logic below.
246 if (Depth == 0 && !V->hasOneUse())
247 DemandedMask = APInt::getAllOnesValue(BitWidth);
249 switch (I->getOpcode()) {
251 computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
253 case Instruction::And:
254 // If either the LHS or the RHS are Zero, the result is zero.
255 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
256 RHSKnownOne, Depth + 1) ||
257 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
258 LHSKnownZero, LHSKnownOne, Depth + 1))
260 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
261 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
263 // If the client is only demanding bits that we know, return the known
265 if ((DemandedMask & ((RHSKnownZero | LHSKnownZero)|
266 (RHSKnownOne & LHSKnownOne))) == DemandedMask)
267 return Constant::getIntegerValue(VTy, RHSKnownOne & LHSKnownOne);
269 // If all of the demanded bits are known 1 on one side, return the other.
270 // These bits cannot contribute to the result of the 'and'.
271 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
272 (DemandedMask & ~LHSKnownZero))
273 return I->getOperand(0);
274 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
275 (DemandedMask & ~RHSKnownZero))
276 return I->getOperand(1);
278 // If all of the demanded bits in the inputs are known zeros, return zero.
279 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
280 return Constant::getNullValue(VTy);
282 // If the RHS is a constant, see if we can simplify it.
283 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
286 // Output known-1 bits are only known if set in both the LHS & RHS.
287 KnownOne = RHSKnownOne & LHSKnownOne;
288 // Output known-0 are known to be clear if zero in either the LHS | RHS.
289 KnownZero = RHSKnownZero | LHSKnownZero;
291 case Instruction::Or:
292 // If either the LHS or the RHS are One, the result is One.
293 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
294 RHSKnownOne, Depth + 1) ||
295 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
296 LHSKnownZero, LHSKnownOne, Depth + 1))
298 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
299 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
301 // If the client is only demanding bits that we know, return the known
303 if ((DemandedMask & ((RHSKnownZero & LHSKnownZero)|
304 (RHSKnownOne | LHSKnownOne))) == DemandedMask)
305 return Constant::getIntegerValue(VTy, RHSKnownOne | LHSKnownOne);
307 // If all of the demanded bits are known zero on one side, return the other.
308 // These bits cannot contribute to the result of the 'or'.
309 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
310 (DemandedMask & ~LHSKnownOne))
311 return I->getOperand(0);
312 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
313 (DemandedMask & ~RHSKnownOne))
314 return I->getOperand(1);
316 // If all of the potentially set bits on one side are known to be set on
317 // the other side, just use the 'other' side.
318 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
319 (DemandedMask & (~RHSKnownZero)))
320 return I->getOperand(0);
321 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
322 (DemandedMask & (~LHSKnownZero)))
323 return I->getOperand(1);
325 // If the RHS is a constant, see if we can simplify it.
326 if (ShrinkDemandedConstant(I, 1, DemandedMask))
329 // Output known-0 bits are only known if clear in both the LHS & RHS.
330 KnownZero = RHSKnownZero & LHSKnownZero;
331 // Output known-1 are known to be set if set in either the LHS | RHS.
332 KnownOne = RHSKnownOne | LHSKnownOne;
334 case Instruction::Xor: {
335 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, RHSKnownZero,
336 RHSKnownOne, Depth + 1) ||
337 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, LHSKnownZero,
338 LHSKnownOne, Depth + 1))
340 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
341 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
343 // Output known-0 bits are known if clear or set in both the LHS & RHS.
344 APInt IKnownZero = (RHSKnownZero & LHSKnownZero) |
345 (RHSKnownOne & LHSKnownOne);
346 // Output known-1 are known to be set if set in only one of the LHS, RHS.
347 APInt IKnownOne = (RHSKnownZero & LHSKnownOne) |
348 (RHSKnownOne & LHSKnownZero);
350 // If the client is only demanding bits that we know, return the known
352 if ((DemandedMask & (IKnownZero|IKnownOne)) == DemandedMask)
353 return Constant::getIntegerValue(VTy, IKnownOne);
355 // If all of the demanded bits are known zero on one side, return the other.
356 // These bits cannot contribute to the result of the 'xor'.
357 if ((DemandedMask & RHSKnownZero) == DemandedMask)
358 return I->getOperand(0);
359 if ((DemandedMask & LHSKnownZero) == DemandedMask)
360 return I->getOperand(1);
362 // If all of the demanded bits are known to be zero on one side or the
363 // other, turn this into an *inclusive* or.
364 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
365 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
367 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
369 return InsertNewInstWith(Or, *I);
372 // If all of the demanded bits on one side are known, and all of the set
373 // bits on that side are also known to be set on the other side, turn this
374 // into an AND, as we know the bits will be cleared.
375 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
376 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
378 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
379 Constant *AndC = Constant::getIntegerValue(VTy,
380 ~RHSKnownOne & DemandedMask);
381 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
382 return InsertNewInstWith(And, *I);
386 // If the RHS is a constant, see if we can simplify it.
387 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
388 if (ShrinkDemandedConstant(I, 1, DemandedMask))
391 // If our LHS is an 'and' and if it has one use, and if any of the bits we
392 // are flipping are known to be set, then the xor is just resetting those
393 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
394 // simplifying both of them.
395 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
396 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
397 isa<ConstantInt>(I->getOperand(1)) &&
398 isa<ConstantInt>(LHSInst->getOperand(1)) &&
399 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
400 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
401 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
402 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
405 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
406 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
407 InsertNewInstWith(NewAnd, *I);
410 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
411 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
412 return InsertNewInstWith(NewXor, *I);
415 // Output known-0 bits are known if clear or set in both the LHS & RHS.
416 KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
417 // Output known-1 are known to be set if set in only one of the LHS, RHS.
418 KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
421 case Instruction::Select:
422 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask, RHSKnownZero,
423 RHSKnownOne, Depth + 1) ||
424 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, LHSKnownZero,
425 LHSKnownOne, Depth + 1))
427 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
428 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
430 // If the operands are constants, see if we can simplify them.
431 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
432 ShrinkDemandedConstant(I, 2, DemandedMask))
435 // Only known if known in both the LHS and RHS.
436 KnownOne = RHSKnownOne & LHSKnownOne;
437 KnownZero = RHSKnownZero & LHSKnownZero;
439 case Instruction::Trunc: {
440 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
441 DemandedMask = DemandedMask.zext(truncBf);
442 KnownZero = KnownZero.zext(truncBf);
443 KnownOne = KnownOne.zext(truncBf);
444 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
445 KnownOne, Depth + 1))
447 DemandedMask = DemandedMask.trunc(BitWidth);
448 KnownZero = KnownZero.trunc(BitWidth);
449 KnownOne = KnownOne.trunc(BitWidth);
450 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
453 case Instruction::BitCast:
454 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
455 return nullptr; // vector->int or fp->int?
457 if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
458 if (VectorType *SrcVTy =
459 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
460 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
461 // Don't touch a bitcast between vectors of different element counts.
464 // Don't touch a scalar-to-vector bitcast.
466 } else if (I->getOperand(0)->getType()->isVectorTy())
467 // Don't touch a vector-to-scalar bitcast.
470 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
471 KnownOne, Depth + 1))
473 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
475 case Instruction::ZExt: {
476 // Compute the bits in the result that are not present in the input.
477 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
479 DemandedMask = DemandedMask.trunc(SrcBitWidth);
480 KnownZero = KnownZero.trunc(SrcBitWidth);
481 KnownOne = KnownOne.trunc(SrcBitWidth);
482 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
483 KnownOne, Depth + 1))
485 DemandedMask = DemandedMask.zext(BitWidth);
486 KnownZero = KnownZero.zext(BitWidth);
487 KnownOne = KnownOne.zext(BitWidth);
488 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
489 // The top bits are known to be zero.
490 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
493 case Instruction::SExt: {
494 // Compute the bits in the result that are not present in the input.
495 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
497 APInt InputDemandedBits = DemandedMask &
498 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
500 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
501 // If any of the sign extended bits are demanded, we know that the sign
503 if ((NewBits & DemandedMask) != 0)
504 InputDemandedBits.setBit(SrcBitWidth-1);
506 InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
507 KnownZero = KnownZero.trunc(SrcBitWidth);
508 KnownOne = KnownOne.trunc(SrcBitWidth);
509 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits, KnownZero,
510 KnownOne, Depth + 1))
512 InputDemandedBits = InputDemandedBits.zext(BitWidth);
513 KnownZero = KnownZero.zext(BitWidth);
514 KnownOne = KnownOne.zext(BitWidth);
515 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
517 // If the sign bit of the input is known set or clear, then we know the
518 // top bits of the result.
520 // If the input sign bit is known zero, or if the NewBits are not demanded
521 // convert this into a zero extension.
522 if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
523 // Convert to ZExt cast
524 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
525 return InsertNewInstWith(NewCast, *I);
526 } else if (KnownOne[SrcBitWidth-1]) { // Input sign bit known set
531 case Instruction::Add: {
532 // Figure out what the input bits are. If the top bits of the and result
533 // are not demanded, then the add doesn't demand them from its input
535 unsigned NLZ = DemandedMask.countLeadingZeros();
537 // If there is a constant on the RHS, there are a variety of xformations
539 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
540 // If null, this should be simplified elsewhere. Some of the xforms here
541 // won't work if the RHS is zero.
545 // If the top bit of the output is demanded, demand everything from the
546 // input. Otherwise, we demand all the input bits except NLZ top bits.
547 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
549 // Find information about known zero/one bits in the input.
550 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
551 LHSKnownZero, LHSKnownOne, Depth + 1))
554 // If the RHS of the add has bits set that can't affect the input, reduce
556 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
559 // Avoid excess work.
560 if (LHSKnownZero == 0 && LHSKnownOne == 0)
563 // Turn it into OR if input bits are zero.
564 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
566 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
568 return InsertNewInstWith(Or, *I);
571 // We can say something about the output known-zero and known-one bits,
572 // depending on potential carries from the input constant and the
573 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
574 // bits set and the RHS constant is 0x01001, then we know we have a known
575 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
577 // To compute this, we first compute the potential carry bits. These are
578 // the bits which may be modified. I'm not aware of a better way to do
580 const APInt &RHSVal = RHS->getValue();
581 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
583 // Now that we know which bits have carries, compute the known-1/0 sets.
585 // Bits are known one if they are known zero in one operand and one in the
586 // other, and there is no input carry.
587 KnownOne = ((LHSKnownZero & RHSVal) |
588 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
590 // Bits are known zero if they are known zero in both operands and there
591 // is no input carry.
592 KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
594 // If the high-bits of this ADD are not demanded, then it does not demand
595 // the high bits of its LHS or RHS.
596 if (DemandedMask[BitWidth-1] == 0) {
597 // Right fill the mask of bits for this ADD to demand the most
598 // significant bit and all those below it.
599 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
600 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
601 LHSKnownZero, LHSKnownOne, Depth + 1) ||
602 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
603 LHSKnownZero, LHSKnownOne, Depth + 1)) {
604 cast<BinaryOperator>(I)->setHasNoSignedWrap(false);
605 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(false);
612 case Instruction::Sub:
613 // If the high-bits of this SUB are not demanded, then it does not demand
614 // the high bits of its LHS or RHS.
615 if (DemandedMask[BitWidth-1] == 0) {
616 // Right fill the mask of bits for this SUB to demand the most
617 // significant bit and all those below it.
618 uint32_t NLZ = DemandedMask.countLeadingZeros();
619 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
620 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
621 LHSKnownZero, LHSKnownOne, Depth + 1) ||
622 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
623 LHSKnownZero, LHSKnownOne, Depth + 1)) {
624 cast<BinaryOperator>(I)->setHasNoSignedWrap(false);
625 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(false);
630 // Otherwise just hand the sub off to computeKnownBits to fill in
631 // the known zeros and ones.
632 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
634 case Instruction::Shl:
635 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
637 Value *VarX; ConstantInt *C1;
638 if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
639 Instruction *Shr = cast<Instruction>(I->getOperand(0));
640 Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
641 KnownZero, KnownOne);
647 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
648 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
650 // If the shift is NUW/NSW, then it does demand the high bits.
651 ShlOperator *IOp = cast<ShlOperator>(I);
652 if (IOp->hasNoSignedWrap())
653 DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
654 else if (IOp->hasNoUnsignedWrap())
655 DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
657 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
658 KnownOne, Depth + 1))
660 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
661 KnownZero <<= ShiftAmt;
662 KnownOne <<= ShiftAmt;
663 // low bits known zero.
665 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
668 case Instruction::LShr:
669 // For a logical shift right
670 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
671 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
673 // Unsigned shift right.
674 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
676 // If the shift is exact, then it does demand the low bits (and knows that
678 if (cast<LShrOperator>(I)->isExact())
679 DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
681 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
682 KnownOne, Depth + 1))
684 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
685 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
686 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
688 // Compute the new bits that are at the top now.
689 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
690 KnownZero |= HighBits; // high bits known zero.
694 case Instruction::AShr:
695 // If this is an arithmetic shift right and only the low-bit is set, we can
696 // always convert this into a logical shr, even if the shift amount is
697 // variable. The low bit of the shift cannot be an input sign bit unless
698 // the shift amount is >= the size of the datatype, which is undefined.
699 if (DemandedMask == 1) {
700 // Perform the logical shift right.
701 Instruction *NewVal = BinaryOperator::CreateLShr(
702 I->getOperand(0), I->getOperand(1), I->getName());
703 return InsertNewInstWith(NewVal, *I);
706 // If the sign bit is the only bit demanded by this ashr, then there is no
707 // need to do it, the shift doesn't change the high bit.
708 if (DemandedMask.isSignBit())
709 return I->getOperand(0);
711 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
712 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
714 // Signed shift right.
715 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
716 // If any of the "high bits" are demanded, we should set the sign bit as
718 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
719 DemandedMaskIn.setBit(BitWidth-1);
721 // If the shift is exact, then it does demand the low bits (and knows that
723 if (cast<AShrOperator>(I)->isExact())
724 DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
726 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
727 KnownOne, Depth + 1))
729 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
730 // Compute the new bits that are at the top now.
731 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
732 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
733 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
735 // Handle the sign bits.
736 APInt SignBit(APInt::getSignBit(BitWidth));
737 // Adjust to where it is now in the mask.
738 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
740 // If the input sign bit is known to be zero, or if none of the top bits
741 // are demanded, turn this into an unsigned shift right.
742 if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
743 (HighBits & ~DemandedMask) == HighBits) {
744 // Perform the logical shift right.
745 BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
747 NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
748 return InsertNewInstWith(NewVal, *I);
749 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
750 KnownOne |= HighBits;
754 case Instruction::SRem:
755 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
756 // X % -1 demands all the bits because we don't want to introduce
757 // INT_MIN % -1 (== undef) by accident.
758 if (Rem->isAllOnesValue())
760 APInt RA = Rem->getValue().abs();
761 if (RA.isPowerOf2()) {
762 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
763 return I->getOperand(0);
765 APInt LowBits = RA - 1;
766 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
767 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2, LHSKnownZero,
768 LHSKnownOne, Depth + 1))
771 // The low bits of LHS are unchanged by the srem.
772 KnownZero = LHSKnownZero & LowBits;
773 KnownOne = LHSKnownOne & LowBits;
775 // If LHS is non-negative or has all low bits zero, then the upper bits
777 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
778 KnownZero |= ~LowBits;
780 // If LHS is negative and not all low bits are zero, then the upper bits
782 if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
783 KnownOne |= ~LowBits;
785 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
789 // The sign bit is the LHS's sign bit, except when the result of the
790 // remainder is zero.
791 if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
792 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
793 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
795 // If it's known zero, our sign bit is also zero.
796 if (LHSKnownZero.isNegative())
797 KnownZero.setBit(KnownZero.getBitWidth() - 1);
800 case Instruction::URem: {
801 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
802 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
803 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes, KnownZero2,
804 KnownOne2, Depth + 1) ||
805 SimplifyDemandedBits(I->getOperandUse(1), AllOnes, KnownZero2,
806 KnownOne2, Depth + 1))
809 unsigned Leaders = KnownZero2.countLeadingOnes();
810 Leaders = std::max(Leaders,
811 KnownZero2.countLeadingOnes());
812 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
815 case Instruction::Call:
816 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
817 switch (II->getIntrinsicID()) {
819 case Intrinsic::bswap: {
820 // If the only bits demanded come from one byte of the bswap result,
821 // just shift the input byte into position to eliminate the bswap.
822 unsigned NLZ = DemandedMask.countLeadingZeros();
823 unsigned NTZ = DemandedMask.countTrailingZeros();
825 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
826 // we need all the bits down to bit 8. Likewise, round NLZ. If we
827 // have 14 leading zeros, round to 8.
830 // If we need exactly one byte, we can do this transformation.
831 if (BitWidth-NLZ-NTZ == 8) {
832 unsigned ResultBit = NTZ;
833 unsigned InputBit = BitWidth-NTZ-8;
835 // Replace this with either a left or right shift to get the byte into
838 if (InputBit > ResultBit)
839 NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
840 ConstantInt::get(I->getType(), InputBit-ResultBit));
842 NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
843 ConstantInt::get(I->getType(), ResultBit-InputBit));
845 return InsertNewInstWith(NewVal, *I);
848 // TODO: Could compute known zero/one bits based on the input.
851 case Intrinsic::x86_sse42_crc32_64_64:
852 KnownZero = APInt::getHighBitsSet(64, 32);
856 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
860 // If the client is only demanding bits that we know, return the known
862 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
863 return Constant::getIntegerValue(VTy, KnownOne);
867 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
868 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
869 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
872 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
873 /// ..., bn}, without considering the specific value X is holding.
874 /// This transformation is legal iff one of following conditions is hold:
875 /// 1) All the bit in S are 0, in this case E1 == E2.
876 /// 2) We don't care those bits in S, per the input DemandedMask.
877 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
880 /// Currently we only test condition 2).
882 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
884 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
885 Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
887 const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
888 const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
889 if (!ShlOp1 || !ShrOp1)
890 return nullptr; // Noop.
892 Value *VarX = Shr->getOperand(0);
893 Type *Ty = VarX->getType();
894 unsigned BitWidth = Ty->getIntegerBitWidth();
895 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
896 return nullptr; // Undef.
898 unsigned ShlAmt = ShlOp1.getZExtValue();
899 unsigned ShrAmt = ShrOp1.getZExtValue();
901 KnownOne.clearAllBits();
902 KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
903 KnownZero &= DemandedMask;
905 APInt BitMask1(APInt::getAllOnesValue(BitWidth));
906 APInt BitMask2(APInt::getAllOnesValue(BitWidth));
908 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
909 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
910 (BitMask1.ashr(ShrAmt) << ShlAmt);
912 if (ShrAmt <= ShlAmt) {
913 BitMask2 <<= (ShlAmt - ShrAmt);
915 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
916 BitMask2.ashr(ShrAmt - ShlAmt);
919 // Check if condition-2 (see the comment to this function) is satified.
920 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
921 if (ShrAmt == ShlAmt)
924 if (!Shr->hasOneUse())
928 if (ShrAmt < ShlAmt) {
929 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
930 New = BinaryOperator::CreateShl(VarX, Amt);
931 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
932 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
933 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
935 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
936 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
937 BinaryOperator::CreateAShr(VarX, Amt);
938 if (cast<BinaryOperator>(Shr)->isExact())
939 New->setIsExact(true);
942 return InsertNewInstWith(New, *Shl);
948 /// SimplifyDemandedVectorElts - The specified value produces a vector with
949 /// any number of elements. DemandedElts contains the set of elements that are
950 /// actually used by the caller. This method analyzes which elements of the
951 /// operand are undef and returns that information in UndefElts.
953 /// If the information about demanded elements can be used to simplify the
954 /// operation, the operation is simplified, then the resultant value is
955 /// returned. This returns null if no change was made.
956 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
959 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
960 APInt EltMask(APInt::getAllOnesValue(VWidth));
961 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
963 if (isa<UndefValue>(V)) {
964 // If the entire vector is undefined, just return this info.
969 if (DemandedElts == 0) { // If nothing is demanded, provide undef.
971 return UndefValue::get(V->getType());
976 // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
977 if (Constant *C = dyn_cast<Constant>(V)) {
978 // Check if this is identity. If so, return 0 since we are not simplifying
980 if (DemandedElts.isAllOnesValue())
983 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
984 Constant *Undef = UndefValue::get(EltTy);
986 SmallVector<Constant*, 16> Elts;
987 for (unsigned i = 0; i != VWidth; ++i) {
988 if (!DemandedElts[i]) { // If not demanded, set to undef.
989 Elts.push_back(Undef);
994 Constant *Elt = C->getAggregateElement(i);
995 if (!Elt) return nullptr;
997 if (isa<UndefValue>(Elt)) { // Already undef.
998 Elts.push_back(Undef);
1000 } else { // Otherwise, defined.
1001 Elts.push_back(Elt);
1005 // If we changed the constant, return it.
1006 Constant *NewCV = ConstantVector::get(Elts);
1007 return NewCV != C ? NewCV : nullptr;
1010 // Limit search depth.
1014 // If multiple users are using the root value, proceed with
1015 // simplification conservatively assuming that all elements
1017 if (!V->hasOneUse()) {
1018 // Quit if we find multiple users of a non-root value though.
1019 // They'll be handled when it's their turn to be visited by
1020 // the main instcombine process.
1022 // TODO: Just compute the UndefElts information recursively.
1025 // Conservatively assume that all elements are needed.
1026 DemandedElts = EltMask;
1029 Instruction *I = dyn_cast<Instruction>(V);
1030 if (!I) return nullptr; // Only analyze instructions.
1032 bool MadeChange = false;
1033 APInt UndefElts2(VWidth, 0);
1035 switch (I->getOpcode()) {
1038 case Instruction::InsertElement: {
1039 // If this is a variable index, we don't know which element it overwrites.
1040 // demand exactly the same input as we produce.
1041 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1043 // Note that we can't propagate undef elt info, because we don't know
1044 // which elt is getting updated.
1045 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1046 UndefElts2, Depth + 1);
1047 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1051 // If this is inserting an element that isn't demanded, remove this
1053 unsigned IdxNo = Idx->getZExtValue();
1054 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1056 return I->getOperand(0);
1059 // Otherwise, the element inserted overwrites whatever was there, so the
1060 // input demanded set is simpler than the output set.
1061 APInt DemandedElts2 = DemandedElts;
1062 DemandedElts2.clearBit(IdxNo);
1063 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1064 UndefElts, Depth + 1);
1065 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1067 // The inserted element is defined.
1068 UndefElts.clearBit(IdxNo);
1071 case Instruction::ShuffleVector: {
1072 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1073 uint64_t LHSVWidth =
1074 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1075 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1076 for (unsigned i = 0; i < VWidth; i++) {
1077 if (DemandedElts[i]) {
1078 unsigned MaskVal = Shuffle->getMaskValue(i);
1079 if (MaskVal != -1u) {
1080 assert(MaskVal < LHSVWidth * 2 &&
1081 "shufflevector mask index out of range!");
1082 if (MaskVal < LHSVWidth)
1083 LeftDemanded.setBit(MaskVal);
1085 RightDemanded.setBit(MaskVal - LHSVWidth);
1090 APInt UndefElts4(LHSVWidth, 0);
1091 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1092 UndefElts4, Depth + 1);
1093 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1095 APInt UndefElts3(LHSVWidth, 0);
1096 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1097 UndefElts3, Depth + 1);
1098 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1100 bool NewUndefElts = false;
1101 for (unsigned i = 0; i < VWidth; i++) {
1102 unsigned MaskVal = Shuffle->getMaskValue(i);
1103 if (MaskVal == -1u) {
1104 UndefElts.setBit(i);
1105 } else if (!DemandedElts[i]) {
1106 NewUndefElts = true;
1107 UndefElts.setBit(i);
1108 } else if (MaskVal < LHSVWidth) {
1109 if (UndefElts4[MaskVal]) {
1110 NewUndefElts = true;
1111 UndefElts.setBit(i);
1114 if (UndefElts3[MaskVal - LHSVWidth]) {
1115 NewUndefElts = true;
1116 UndefElts.setBit(i);
1122 // Add additional discovered undefs.
1123 SmallVector<Constant*, 16> Elts;
1124 for (unsigned i = 0; i < VWidth; ++i) {
1126 Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1128 Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1129 Shuffle->getMaskValue(i)));
1131 I->setOperand(2, ConstantVector::get(Elts));
1136 case Instruction::Select: {
1137 APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
1138 if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
1139 for (unsigned i = 0; i < VWidth; i++) {
1140 if (CV->getAggregateElement(i)->isNullValue())
1141 LeftDemanded.clearBit(i);
1143 RightDemanded.clearBit(i);
1147 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded, UndefElts,
1149 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1151 TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
1152 UndefElts2, Depth + 1);
1153 if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
1155 // Output elements are undefined if both are undefined.
1156 UndefElts &= UndefElts2;
1159 case Instruction::BitCast: {
1160 // Vector->vector casts only.
1161 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1163 unsigned InVWidth = VTy->getNumElements();
1164 APInt InputDemandedElts(InVWidth, 0);
1167 if (VWidth == InVWidth) {
1168 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1169 // elements as are demanded of us.
1171 InputDemandedElts = DemandedElts;
1172 } else if (VWidth > InVWidth) {
1176 // If there are more elements in the result than there are in the source,
1177 // then an input element is live if any of the corresponding output
1178 // elements are live.
1179 Ratio = VWidth/InVWidth;
1180 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1181 if (DemandedElts[OutIdx])
1182 InputDemandedElts.setBit(OutIdx/Ratio);
1188 // If there are more elements in the source than there are in the result,
1189 // then an input element is live if the corresponding output element is
1191 Ratio = InVWidth/VWidth;
1192 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1193 if (DemandedElts[InIdx/Ratio])
1194 InputDemandedElts.setBit(InIdx);
1197 // div/rem demand all inputs, because they don't want divide by zero.
1198 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1199 UndefElts2, Depth + 1);
1201 I->setOperand(0, TmpV);
1205 UndefElts = UndefElts2;
1206 if (VWidth > InVWidth) {
1207 llvm_unreachable("Unimp");
1208 // If there are more elements in the result than there are in the source,
1209 // then an output element is undef if the corresponding input element is
1211 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1212 if (UndefElts2[OutIdx/Ratio])
1213 UndefElts.setBit(OutIdx);
1214 } else if (VWidth < InVWidth) {
1215 llvm_unreachable("Unimp");
1216 // If there are more elements in the source than there are in the result,
1217 // then a result element is undef if all of the corresponding input
1218 // elements are undef.
1219 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1220 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1221 if (!UndefElts2[InIdx]) // Not undef?
1222 UndefElts.clearBit(InIdx/Ratio); // Clear undef bit.
1226 case Instruction::And:
1227 case Instruction::Or:
1228 case Instruction::Xor:
1229 case Instruction::Add:
1230 case Instruction::Sub:
1231 case Instruction::Mul:
1232 // div/rem demand all inputs, because they don't want divide by zero.
1233 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, UndefElts,
1235 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1236 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1237 UndefElts2, Depth + 1);
1238 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1240 // Output elements are undefined if both are undefined. Consider things
1241 // like undef&0. The result is known zero, not undef.
1242 UndefElts &= UndefElts2;
1244 case Instruction::FPTrunc:
1245 case Instruction::FPExt:
1246 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, UndefElts,
1248 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1251 case Instruction::Call: {
1252 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1254 switch (II->getIntrinsicID()) {
1257 // Binary vector operations that work column-wise. A dest element is a
1258 // function of the corresponding input elements from the two inputs.
1259 case Intrinsic::x86_sse_sub_ss:
1260 case Intrinsic::x86_sse_mul_ss:
1261 case Intrinsic::x86_sse_min_ss:
1262 case Intrinsic::x86_sse_max_ss:
1263 case Intrinsic::x86_sse2_sub_sd:
1264 case Intrinsic::x86_sse2_mul_sd:
1265 case Intrinsic::x86_sse2_min_sd:
1266 case Intrinsic::x86_sse2_max_sd:
1267 TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
1268 UndefElts, Depth + 1);
1269 if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
1270 TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
1271 UndefElts2, Depth + 1);
1272 if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
1274 // If only the low elt is demanded and this is a scalarizable intrinsic,
1275 // scalarize it now.
1276 if (DemandedElts == 1) {
1277 switch (II->getIntrinsicID()) {
1279 case Intrinsic::x86_sse_sub_ss:
1280 case Intrinsic::x86_sse_mul_ss:
1281 case Intrinsic::x86_sse2_sub_sd:
1282 case Intrinsic::x86_sse2_mul_sd:
1283 // TODO: Lower MIN/MAX/ABS/etc
1284 Value *LHS = II->getArgOperand(0);
1285 Value *RHS = II->getArgOperand(1);
1286 // Extract the element as scalars.
1287 LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
1288 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1289 RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
1290 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1292 switch (II->getIntrinsicID()) {
1293 default: llvm_unreachable("Case stmts out of sync!");
1294 case Intrinsic::x86_sse_sub_ss:
1295 case Intrinsic::x86_sse2_sub_sd:
1296 TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
1297 II->getName()), *II);
1299 case Intrinsic::x86_sse_mul_ss:
1300 case Intrinsic::x86_sse2_mul_sd:
1301 TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
1302 II->getName()), *II);
1307 InsertElementInst::Create(
1308 UndefValue::get(II->getType()), TmpV,
1309 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1311 InsertNewInstWith(New, *II);
1316 // Output elements are undefined if both are undefined. Consider things
1317 // like undef&0. The result is known zero, not undef.
1318 UndefElts &= UndefElts2;
1324 return MadeChange ? I : nullptr;