Make use of @llvm.assume in ValueTracking (computeKnownBits, etc.)
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineSimplifyDemanded.cpp
1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains logic for simplifying instructions based on information
11 // about how they are used.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstCombine.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19
20 using namespace llvm;
21 using namespace llvm::PatternMatch;
22
23 #define DEBUG_TYPE "instcombine"
24
25 /// ShrinkDemandedConstant - Check to see if the specified operand of the
26 /// specified instruction is a constant integer.  If so, check to see if there
27 /// are any bits set in the constant that are not demanded.  If so, shrink the
28 /// constant and return true.
29 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
30                                    APInt Demanded) {
31   assert(I && "No instruction?");
32   assert(OpNo < I->getNumOperands() && "Operand index too large");
33
34   // If the operand is not a constant integer, nothing to do.
35   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
36   if (!OpC) return false;
37
38   // If there are no bits set that aren't demanded, nothing to do.
39   Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
40   if ((~Demanded & OpC->getValue()) == 0)
41     return false;
42
43   // This instruction is producing bits that are not demanded. Shrink the RHS.
44   Demanded &= OpC->getValue();
45   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
46
47   // If either 'nsw' or 'nuw' is set and the constant is negative,
48   // removing *any* bits from the constant could make overflow occur.
49   // Remove 'nsw' and 'nuw' from the instruction in this case.
50   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
51     assert(OBO->getOpcode() == Instruction::Add);
52     if (OBO->hasNoSignedWrap() || OBO->hasNoUnsignedWrap()) {
53       if (OpC->getValue().isNegative()) {
54         cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
55         cast<BinaryOperator>(OBO)->setHasNoUnsignedWrap(false);
56       }
57     }
58   }
59
60   return true;
61 }
62
63
64
65 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
66 /// SimplifyDemandedBits knows about.  See if the instruction has any
67 /// properties that allow us to simplify its operands.
68 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
69   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
70   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
71   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
72
73   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
74                                      KnownZero, KnownOne, 0, &Inst);
75   if (!V) return false;
76   if (V == &Inst) return true;
77   ReplaceInstUsesWith(Inst, V);
78   return true;
79 }
80
81 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
82 /// specified instruction operand if possible, updating it in place.  It returns
83 /// true if it made any change and false otherwise.
84 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
85                                         APInt &KnownZero, APInt &KnownOne,
86                                         unsigned Depth) {
87   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
88                                           KnownZero, KnownOne, Depth,
89                                           dyn_cast<Instruction>(U.getUser()));
90   if (!NewVal) return false;
91   U = NewVal;
92   return true;
93 }
94
95
96 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
97 /// value based on the demanded bits.  When this function is called, it is known
98 /// that only the bits set in DemandedMask of the result of V are ever used
99 /// downstream. Consequently, depending on the mask and V, it may be possible
100 /// to replace V with a constant or one of its operands. In such cases, this
101 /// function does the replacement and returns true. In all other cases, it
102 /// returns false after analyzing the expression and setting KnownOne and known
103 /// to be one in the expression.  KnownZero contains all the bits that are known
104 /// to be zero in the expression. These are provided to potentially allow the
105 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
106 /// the expression. KnownOne and KnownZero always follow the invariant that
107 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
108 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
109 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
110 /// and KnownOne must all be the same.
111 ///
112 /// This returns null if it did not change anything and it permits no
113 /// simplification.  This returns V itself if it did some simplification of V's
114 /// operands based on the information about what bits are demanded. This returns
115 /// some other non-null value if it found out that V is equal to another value
116 /// in the context where the specified bits are demanded, but not for all users.
117 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
118                                              APInt &KnownZero, APInt &KnownOne,
119                                              unsigned Depth,
120                                              Instruction *CxtI) {
121   assert(V != nullptr && "Null pointer of Value???");
122   assert(Depth <= 6 && "Limit Search Depth");
123   uint32_t BitWidth = DemandedMask.getBitWidth();
124   Type *VTy = V->getType();
125   assert((DL || !VTy->isPointerTy()) &&
126          "SimplifyDemandedBits needs to know bit widths!");
127   assert((!DL || DL->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
128          (!VTy->isIntOrIntVectorTy() ||
129           VTy->getScalarSizeInBits() == BitWidth) &&
130          KnownZero.getBitWidth() == BitWidth &&
131          KnownOne.getBitWidth() == BitWidth &&
132          "Value *V, DemandedMask, KnownZero and KnownOne "
133          "must have same BitWidth");
134   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
135     // We know all of the bits for a constant!
136     KnownOne = CI->getValue() & DemandedMask;
137     KnownZero = ~KnownOne & DemandedMask;
138     return nullptr;
139   }
140   if (isa<ConstantPointerNull>(V)) {
141     // We know all of the bits for a constant!
142     KnownOne.clearAllBits();
143     KnownZero = DemandedMask;
144     return nullptr;
145   }
146
147   KnownZero.clearAllBits();
148   KnownOne.clearAllBits();
149   if (DemandedMask == 0) {   // Not demanding any bits from V.
150     if (isa<UndefValue>(V))
151       return nullptr;
152     return UndefValue::get(VTy);
153   }
154
155   if (Depth == 6)        // Limit search depth.
156     return nullptr;
157
158   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
159   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
160
161   Instruction *I = dyn_cast<Instruction>(V);
162   if (!I) {
163     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
164     return nullptr;        // Only analyze instructions.
165   }
166
167   // If there are multiple uses of this value and we aren't at the root, then
168   // we can't do any simplifications of the operands, because DemandedMask
169   // only reflects the bits demanded by *one* of the users.
170   if (Depth != 0 && !I->hasOneUse()) {
171     // Despite the fact that we can't simplify this instruction in all User's
172     // context, we can at least compute the knownzero/knownone bits, and we can
173     // do simplifications that apply to *just* the one user if we know that
174     // this instruction has a simpler value in that context.
175     if (I->getOpcode() == Instruction::And) {
176       // If either the LHS or the RHS are Zero, the result is zero.
177       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
178                        CxtI);
179       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
180                        CxtI);
181
182       // If all of the demanded bits are known 1 on one side, return the other.
183       // These bits cannot contribute to the result of the 'and' in this
184       // context.
185       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
186           (DemandedMask & ~LHSKnownZero))
187         return I->getOperand(0);
188       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
189           (DemandedMask & ~RHSKnownZero))
190         return I->getOperand(1);
191
192       // If all of the demanded bits in the inputs are known zeros, return zero.
193       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
194         return Constant::getNullValue(VTy);
195
196     } else if (I->getOpcode() == Instruction::Or) {
197       // We can simplify (X|Y) -> X or Y in the user's context if we know that
198       // only bits from X or Y are demanded.
199
200       // If either the LHS or the RHS are One, the result is One.
201       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
202                        CxtI);
203       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
204                        CxtI);
205
206       // If all of the demanded bits are known zero on one side, return the
207       // other.  These bits cannot contribute to the result of the 'or' in this
208       // context.
209       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
210           (DemandedMask & ~LHSKnownOne))
211         return I->getOperand(0);
212       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
213           (DemandedMask & ~RHSKnownOne))
214         return I->getOperand(1);
215
216       // If all of the potentially set bits on one side are known to be set on
217       // the other side, just use the 'other' side.
218       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
219           (DemandedMask & (~RHSKnownZero)))
220         return I->getOperand(0);
221       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
222           (DemandedMask & (~LHSKnownZero)))
223         return I->getOperand(1);
224     } else if (I->getOpcode() == Instruction::Xor) {
225       // We can simplify (X^Y) -> X or Y in the user's context if we know that
226       // only bits from X or Y are demanded.
227
228       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
229                        CxtI);
230       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
231                        CxtI);
232
233       // If all of the demanded bits are known zero on one side, return the
234       // other.
235       if ((DemandedMask & RHSKnownZero) == DemandedMask)
236         return I->getOperand(0);
237       if ((DemandedMask & LHSKnownZero) == DemandedMask)
238         return I->getOperand(1);
239     }
240
241     // Compute the KnownZero/KnownOne bits to simplify things downstream.
242     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
243     return nullptr;
244   }
245
246   // If this is the root being simplified, allow it to have multiple uses,
247   // just set the DemandedMask to all bits so that we can try to simplify the
248   // operands.  This allows visitTruncInst (for example) to simplify the
249   // operand of a trunc without duplicating all the logic below.
250   if (Depth == 0 && !V->hasOneUse())
251     DemandedMask = APInt::getAllOnesValue(BitWidth);
252
253   switch (I->getOpcode()) {
254   default:
255     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
256     break;
257   case Instruction::And:
258     // If either the LHS or the RHS are Zero, the result is zero.
259     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
260                              RHSKnownZero, RHSKnownOne, Depth+1) ||
261         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
262                              LHSKnownZero, LHSKnownOne, Depth+1))
263       return I;
264     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
265     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
266
267     // If all of the demanded bits are known 1 on one side, return the other.
268     // These bits cannot contribute to the result of the 'and'.
269     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
270         (DemandedMask & ~LHSKnownZero))
271       return I->getOperand(0);
272     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
273         (DemandedMask & ~RHSKnownZero))
274       return I->getOperand(1);
275
276     // If all of the demanded bits in the inputs are known zeros, return zero.
277     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
278       return Constant::getNullValue(VTy);
279
280     // If the RHS is a constant, see if we can simplify it.
281     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
282       return I;
283
284     // Output known-1 bits are only known if set in both the LHS & RHS.
285     KnownOne = RHSKnownOne & LHSKnownOne;
286     // Output known-0 are known to be clear if zero in either the LHS | RHS.
287     KnownZero = RHSKnownZero | LHSKnownZero;
288     break;
289   case Instruction::Or:
290     // If either the LHS or the RHS are One, the result is One.
291     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
292                              RHSKnownZero, RHSKnownOne, Depth+1) ||
293         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
294                              LHSKnownZero, LHSKnownOne, Depth+1))
295       return I;
296     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
297     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
298
299     // If all of the demanded bits are known zero on one side, return the other.
300     // These bits cannot contribute to the result of the 'or'.
301     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
302         (DemandedMask & ~LHSKnownOne))
303       return I->getOperand(0);
304     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
305         (DemandedMask & ~RHSKnownOne))
306       return I->getOperand(1);
307
308     // If all of the potentially set bits on one side are known to be set on
309     // the other side, just use the 'other' side.
310     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
311         (DemandedMask & (~RHSKnownZero)))
312       return I->getOperand(0);
313     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
314         (DemandedMask & (~LHSKnownZero)))
315       return I->getOperand(1);
316
317     // If the RHS is a constant, see if we can simplify it.
318     if (ShrinkDemandedConstant(I, 1, DemandedMask))
319       return I;
320
321     // Output known-0 bits are only known if clear in both the LHS & RHS.
322     KnownZero = RHSKnownZero & LHSKnownZero;
323     // Output known-1 are known to be set if set in either the LHS | RHS.
324     KnownOne = RHSKnownOne | LHSKnownOne;
325     break;
326   case Instruction::Xor: {
327     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
328                              RHSKnownZero, RHSKnownOne, Depth+1) ||
329         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
330                              LHSKnownZero, LHSKnownOne, Depth+1))
331       return I;
332     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
333     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
334
335     // If all of the demanded bits are known zero on one side, return the other.
336     // These bits cannot contribute to the result of the 'xor'.
337     if ((DemandedMask & RHSKnownZero) == DemandedMask)
338       return I->getOperand(0);
339     if ((DemandedMask & LHSKnownZero) == DemandedMask)
340       return I->getOperand(1);
341
342     // If all of the demanded bits are known to be zero on one side or the
343     // other, turn this into an *inclusive* or.
344     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
345     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
346       Instruction *Or =
347         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
348                                  I->getName());
349       return InsertNewInstWith(Or, *I);
350     }
351
352     // If all of the demanded bits on one side are known, and all of the set
353     // bits on that side are also known to be set on the other side, turn this
354     // into an AND, as we know the bits will be cleared.
355     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
356     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
357       // all known
358       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
359         Constant *AndC = Constant::getIntegerValue(VTy,
360                                                    ~RHSKnownOne & DemandedMask);
361         Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
362         return InsertNewInstWith(And, *I);
363       }
364     }
365
366     // If the RHS is a constant, see if we can simplify it.
367     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
368     if (ShrinkDemandedConstant(I, 1, DemandedMask))
369       return I;
370
371     // If our LHS is an 'and' and if it has one use, and if any of the bits we
372     // are flipping are known to be set, then the xor is just resetting those
373     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
374     // simplifying both of them.
375     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
376       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
377           isa<ConstantInt>(I->getOperand(1)) &&
378           isa<ConstantInt>(LHSInst->getOperand(1)) &&
379           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
380         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
381         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
382         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
383
384         Constant *AndC =
385           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
386         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
387         InsertNewInstWith(NewAnd, *I);
388
389         Constant *XorC =
390           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
391         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
392         return InsertNewInstWith(NewXor, *I);
393       }
394
395     // Output known-0 bits are known if clear or set in both the LHS & RHS.
396     KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
397     // Output known-1 are known to be set if set in only one of the LHS, RHS.
398     KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
399     break;
400   }
401   case Instruction::Select:
402     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
403                              RHSKnownZero, RHSKnownOne, Depth+1) ||
404         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
405                              LHSKnownZero, LHSKnownOne, Depth+1))
406       return I;
407     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
408     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
409
410     // If the operands are constants, see if we can simplify them.
411     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
412         ShrinkDemandedConstant(I, 2, DemandedMask))
413       return I;
414
415     // Only known if known in both the LHS and RHS.
416     KnownOne = RHSKnownOne & LHSKnownOne;
417     KnownZero = RHSKnownZero & LHSKnownZero;
418     break;
419   case Instruction::Trunc: {
420     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
421     DemandedMask = DemandedMask.zext(truncBf);
422     KnownZero = KnownZero.zext(truncBf);
423     KnownOne = KnownOne.zext(truncBf);
424     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
425                              KnownZero, KnownOne, Depth+1))
426       return I;
427     DemandedMask = DemandedMask.trunc(BitWidth);
428     KnownZero = KnownZero.trunc(BitWidth);
429     KnownOne = KnownOne.trunc(BitWidth);
430     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
431     break;
432   }
433   case Instruction::BitCast:
434     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
435       return nullptr;  // vector->int or fp->int?
436
437     if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
438       if (VectorType *SrcVTy =
439             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
440         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
441           // Don't touch a bitcast between vectors of different element counts.
442           return nullptr;
443       } else
444         // Don't touch a scalar-to-vector bitcast.
445         return nullptr;
446     } else if (I->getOperand(0)->getType()->isVectorTy())
447       // Don't touch a vector-to-scalar bitcast.
448       return nullptr;
449
450     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
451                              KnownZero, KnownOne, Depth+1))
452       return I;
453     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
454     break;
455   case Instruction::ZExt: {
456     // Compute the bits in the result that are not present in the input.
457     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
458
459     DemandedMask = DemandedMask.trunc(SrcBitWidth);
460     KnownZero = KnownZero.trunc(SrcBitWidth);
461     KnownOne = KnownOne.trunc(SrcBitWidth);
462     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
463                              KnownZero, KnownOne, Depth+1))
464       return I;
465     DemandedMask = DemandedMask.zext(BitWidth);
466     KnownZero = KnownZero.zext(BitWidth);
467     KnownOne = KnownOne.zext(BitWidth);
468     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
469     // The top bits are known to be zero.
470     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
471     break;
472   }
473   case Instruction::SExt: {
474     // Compute the bits in the result that are not present in the input.
475     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
476
477     APInt InputDemandedBits = DemandedMask &
478                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
479
480     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
481     // If any of the sign extended bits are demanded, we know that the sign
482     // bit is demanded.
483     if ((NewBits & DemandedMask) != 0)
484       InputDemandedBits.setBit(SrcBitWidth-1);
485
486     InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
487     KnownZero = KnownZero.trunc(SrcBitWidth);
488     KnownOne = KnownOne.trunc(SrcBitWidth);
489     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
490                              KnownZero, KnownOne, Depth+1))
491       return I;
492     InputDemandedBits = InputDemandedBits.zext(BitWidth);
493     KnownZero = KnownZero.zext(BitWidth);
494     KnownOne = KnownOne.zext(BitWidth);
495     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
496
497     // If the sign bit of the input is known set or clear, then we know the
498     // top bits of the result.
499
500     // If the input sign bit is known zero, or if the NewBits are not demanded
501     // convert this into a zero extension.
502     if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
503       // Convert to ZExt cast
504       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
505       return InsertNewInstWith(NewCast, *I);
506     } else if (KnownOne[SrcBitWidth-1]) {    // Input sign bit known set
507       KnownOne |= NewBits;
508     }
509     break;
510   }
511   case Instruction::Add: {
512     // Figure out what the input bits are.  If the top bits of the and result
513     // are not demanded, then the add doesn't demand them from its input
514     // either.
515     unsigned NLZ = DemandedMask.countLeadingZeros();
516
517     // If there is a constant on the RHS, there are a variety of xformations
518     // we can do.
519     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
520       // If null, this should be simplified elsewhere.  Some of the xforms here
521       // won't work if the RHS is zero.
522       if (RHS->isZero())
523         break;
524
525       // If the top bit of the output is demanded, demand everything from the
526       // input.  Otherwise, we demand all the input bits except NLZ top bits.
527       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
528
529       // Find information about known zero/one bits in the input.
530       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
531                                LHSKnownZero, LHSKnownOne, Depth+1))
532         return I;
533
534       // If the RHS of the add has bits set that can't affect the input, reduce
535       // the constant.
536       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
537         return I;
538
539       // Avoid excess work.
540       if (LHSKnownZero == 0 && LHSKnownOne == 0)
541         break;
542
543       // Turn it into OR if input bits are zero.
544       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
545         Instruction *Or =
546           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
547                                    I->getName());
548         return InsertNewInstWith(Or, *I);
549       }
550
551       // We can say something about the output known-zero and known-one bits,
552       // depending on potential carries from the input constant and the
553       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
554       // bits set and the RHS constant is 0x01001, then we know we have a known
555       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
556
557       // To compute this, we first compute the potential carry bits.  These are
558       // the bits which may be modified.  I'm not aware of a better way to do
559       // this scan.
560       const APInt &RHSVal = RHS->getValue();
561       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
562
563       // Now that we know which bits have carries, compute the known-1/0 sets.
564
565       // Bits are known one if they are known zero in one operand and one in the
566       // other, and there is no input carry.
567       KnownOne = ((LHSKnownZero & RHSVal) |
568                   (LHSKnownOne & ~RHSVal)) & ~CarryBits;
569
570       // Bits are known zero if they are known zero in both operands and there
571       // is no input carry.
572       KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
573     } else {
574       // If the high-bits of this ADD are not demanded, then it does not demand
575       // the high bits of its LHS or RHS.
576       if (DemandedMask[BitWidth-1] == 0) {
577         // Right fill the mask of bits for this ADD to demand the most
578         // significant bit and all those below it.
579         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
580         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
581                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
582             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
583                                  LHSKnownZero, LHSKnownOne, Depth+1))
584           return I;
585       }
586     }
587     break;
588   }
589   case Instruction::Sub:
590     // If the high-bits of this SUB are not demanded, then it does not demand
591     // the high bits of its LHS or RHS.
592     if (DemandedMask[BitWidth-1] == 0) {
593       // Right fill the mask of bits for this SUB to demand the most
594       // significant bit and all those below it.
595       uint32_t NLZ = DemandedMask.countLeadingZeros();
596       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
597       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
598                                LHSKnownZero, LHSKnownOne, Depth+1) ||
599           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
600                                LHSKnownZero, LHSKnownOne, Depth+1))
601         return I;
602     }
603
604     // Otherwise just hand the sub off to computeKnownBits to fill in
605     // the known zeros and ones.
606     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
607
608     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
609     // zero.
610     if (ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(0))) {
611       APInt I0 = C0->getValue();
612       if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
613         Instruction *Xor = BinaryOperator::CreateXor(I->getOperand(1), C0);
614         return InsertNewInstWith(Xor, *I);
615       }
616     }
617     break;
618   case Instruction::Shl:
619     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
620       {
621         Value *VarX; ConstantInt *C1;
622         if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
623           Instruction *Shr = cast<Instruction>(I->getOperand(0));
624           Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
625                                                 KnownZero, KnownOne);
626           if (R)
627             return R;
628         }
629       }
630
631       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
632       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
633
634       // If the shift is NUW/NSW, then it does demand the high bits.
635       ShlOperator *IOp = cast<ShlOperator>(I);
636       if (IOp->hasNoSignedWrap())
637         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
638       else if (IOp->hasNoUnsignedWrap())
639         DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
640
641       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
642                                KnownZero, KnownOne, Depth+1))
643         return I;
644       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
645       KnownZero <<= ShiftAmt;
646       KnownOne  <<= ShiftAmt;
647       // low bits known zero.
648       if (ShiftAmt)
649         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
650     }
651     break;
652   case Instruction::LShr:
653     // For a logical shift right
654     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
655       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
656
657       // Unsigned shift right.
658       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
659
660       // If the shift is exact, then it does demand the low bits (and knows that
661       // they are zero).
662       if (cast<LShrOperator>(I)->isExact())
663         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
664
665       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
666                                KnownZero, KnownOne, Depth+1))
667         return I;
668       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
669       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
670       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
671       if (ShiftAmt) {
672         // Compute the new bits that are at the top now.
673         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
674         KnownZero |= HighBits;  // high bits known zero.
675       }
676     }
677     break;
678   case Instruction::AShr:
679     // If this is an arithmetic shift right and only the low-bit is set, we can
680     // always convert this into a logical shr, even if the shift amount is
681     // variable.  The low bit of the shift cannot be an input sign bit unless
682     // the shift amount is >= the size of the datatype, which is undefined.
683     if (DemandedMask == 1) {
684       // Perform the logical shift right.
685       Instruction *NewVal = BinaryOperator::CreateLShr(
686                         I->getOperand(0), I->getOperand(1), I->getName());
687       return InsertNewInstWith(NewVal, *I);
688     }
689
690     // If the sign bit is the only bit demanded by this ashr, then there is no
691     // need to do it, the shift doesn't change the high bit.
692     if (DemandedMask.isSignBit())
693       return I->getOperand(0);
694
695     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
696       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
697
698       // Signed shift right.
699       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
700       // If any of the "high bits" are demanded, we should set the sign bit as
701       // demanded.
702       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
703         DemandedMaskIn.setBit(BitWidth-1);
704
705       // If the shift is exact, then it does demand the low bits (and knows that
706       // they are zero).
707       if (cast<AShrOperator>(I)->isExact())
708         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
709
710       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
711                                KnownZero, KnownOne, Depth+1))
712         return I;
713       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
714       // Compute the new bits that are at the top now.
715       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
716       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
717       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
718
719       // Handle the sign bits.
720       APInt SignBit(APInt::getSignBit(BitWidth));
721       // Adjust to where it is now in the mask.
722       SignBit = APIntOps::lshr(SignBit, ShiftAmt);
723
724       // If the input sign bit is known to be zero, or if none of the top bits
725       // are demanded, turn this into an unsigned shift right.
726       if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
727           (HighBits & ~DemandedMask) == HighBits) {
728         // Perform the logical shift right.
729         BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
730                                                             SA, I->getName());
731         NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
732         return InsertNewInstWith(NewVal, *I);
733       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
734         KnownOne |= HighBits;
735       }
736     }
737     break;
738   case Instruction::SRem:
739     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
740       // X % -1 demands all the bits because we don't want to introduce
741       // INT_MIN % -1 (== undef) by accident.
742       if (Rem->isAllOnesValue())
743         break;
744       APInt RA = Rem->getValue().abs();
745       if (RA.isPowerOf2()) {
746         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
747           return I->getOperand(0);
748
749         APInt LowBits = RA - 1;
750         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
751         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
752                                  LHSKnownZero, LHSKnownOne, Depth+1))
753           return I;
754
755         // The low bits of LHS are unchanged by the srem.
756         KnownZero = LHSKnownZero & LowBits;
757         KnownOne = LHSKnownOne & LowBits;
758
759         // If LHS is non-negative or has all low bits zero, then the upper bits
760         // are all zero.
761         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
762           KnownZero |= ~LowBits;
763
764         // If LHS is negative and not all low bits are zero, then the upper bits
765         // are all one.
766         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
767           KnownOne |= ~LowBits;
768
769         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
770       }
771     }
772
773     // The sign bit is the LHS's sign bit, except when the result of the
774     // remainder is zero.
775     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
776       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
777       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
778                        CxtI);
779       // If it's known zero, our sign bit is also zero.
780       if (LHSKnownZero.isNegative())
781         KnownZero.setBit(KnownZero.getBitWidth() - 1);
782     }
783     break;
784   case Instruction::URem: {
785     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
786     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
787     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
788                              KnownZero2, KnownOne2, Depth+1) ||
789         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
790                              KnownZero2, KnownOne2, Depth+1))
791       return I;
792
793     unsigned Leaders = KnownZero2.countLeadingOnes();
794     Leaders = std::max(Leaders,
795                        KnownZero2.countLeadingOnes());
796     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
797     break;
798   }
799   case Instruction::Call:
800     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
801       switch (II->getIntrinsicID()) {
802       default: break;
803       case Intrinsic::bswap: {
804         // If the only bits demanded come from one byte of the bswap result,
805         // just shift the input byte into position to eliminate the bswap.
806         unsigned NLZ = DemandedMask.countLeadingZeros();
807         unsigned NTZ = DemandedMask.countTrailingZeros();
808
809         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
810         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
811         // have 14 leading zeros, round to 8.
812         NLZ &= ~7;
813         NTZ &= ~7;
814         // If we need exactly one byte, we can do this transformation.
815         if (BitWidth-NLZ-NTZ == 8) {
816           unsigned ResultBit = NTZ;
817           unsigned InputBit = BitWidth-NTZ-8;
818
819           // Replace this with either a left or right shift to get the byte into
820           // the right place.
821           Instruction *NewVal;
822           if (InputBit > ResultBit)
823             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
824                     ConstantInt::get(I->getType(), InputBit-ResultBit));
825           else
826             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
827                     ConstantInt::get(I->getType(), ResultBit-InputBit));
828           NewVal->takeName(I);
829           return InsertNewInstWith(NewVal, *I);
830         }
831
832         // TODO: Could compute known zero/one bits based on the input.
833         break;
834       }
835       case Intrinsic::x86_sse42_crc32_64_64:
836         KnownZero = APInt::getHighBitsSet(64, 32);
837         return nullptr;
838       }
839     }
840     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
841     break;
842   }
843
844   // If the client is only demanding bits that we know, return the known
845   // constant.
846   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
847     return Constant::getIntegerValue(VTy, KnownOne);
848   return nullptr;
849 }
850
851 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
852 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
853 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
854 /// of "C2-C1".
855 ///
856 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
857 /// ..., bn}, without considering the specific value X is holding.
858 /// This transformation is legal iff one of following conditions is hold:
859 ///  1) All the bit in S are 0, in this case E1 == E2.
860 ///  2) We don't care those bits in S, per the input DemandedMask.
861 ///  3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
862 ///     rest bits.
863 ///
864 /// Currently we only test condition 2).
865 ///
866 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
867 /// not successful.
868 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
869   Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
870
871   const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
872   const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
873   if (!ShlOp1 || !ShrOp1)
874       return nullptr; // Noop.
875
876   Value *VarX = Shr->getOperand(0);
877   Type *Ty = VarX->getType();
878   unsigned BitWidth = Ty->getIntegerBitWidth();
879   if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
880     return nullptr; // Undef.
881
882   unsigned ShlAmt = ShlOp1.getZExtValue();
883   unsigned ShrAmt = ShrOp1.getZExtValue();
884
885   KnownOne.clearAllBits();
886   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
887   KnownZero &= DemandedMask;
888
889   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
890   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
891
892   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
893   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
894                       (BitMask1.ashr(ShrAmt) << ShlAmt);
895
896   if (ShrAmt <= ShlAmt) {
897     BitMask2 <<= (ShlAmt - ShrAmt);
898   } else {
899     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
900                         BitMask2.ashr(ShrAmt - ShlAmt);
901   }
902
903   // Check if condition-2 (see the comment to this function) is satified.
904   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
905     if (ShrAmt == ShlAmt)
906       return VarX;
907
908     if (!Shr->hasOneUse())
909       return nullptr;
910
911     BinaryOperator *New;
912     if (ShrAmt < ShlAmt) {
913       Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
914       New = BinaryOperator::CreateShl(VarX, Amt);
915       BinaryOperator *Orig = cast<BinaryOperator>(Shl);
916       New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
917       New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
918     } else {
919       Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
920       New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
921                      BinaryOperator::CreateAShr(VarX, Amt);
922       if (cast<BinaryOperator>(Shr)->isExact())
923         New->setIsExact(true);
924     }
925
926     return InsertNewInstWith(New, *Shl);
927   }
928
929   return nullptr;
930 }
931
932 /// SimplifyDemandedVectorElts - The specified value produces a vector with
933 /// any number of elements. DemandedElts contains the set of elements that are
934 /// actually used by the caller.  This method analyzes which elements of the
935 /// operand are undef and returns that information in UndefElts.
936 ///
937 /// If the information about demanded elements can be used to simplify the
938 /// operation, the operation is simplified, then the resultant value is
939 /// returned.  This returns null if no change was made.
940 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
941                                                 APInt &UndefElts,
942                                                 unsigned Depth) {
943   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
944   APInt EltMask(APInt::getAllOnesValue(VWidth));
945   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
946
947   if (isa<UndefValue>(V)) {
948     // If the entire vector is undefined, just return this info.
949     UndefElts = EltMask;
950     return nullptr;
951   }
952
953   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
954     UndefElts = EltMask;
955     return UndefValue::get(V->getType());
956   }
957
958   UndefElts = 0;
959
960   // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
961   if (Constant *C = dyn_cast<Constant>(V)) {
962     // Check if this is identity. If so, return 0 since we are not simplifying
963     // anything.
964     if (DemandedElts.isAllOnesValue())
965       return nullptr;
966
967     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
968     Constant *Undef = UndefValue::get(EltTy);
969
970     SmallVector<Constant*, 16> Elts;
971     for (unsigned i = 0; i != VWidth; ++i) {
972       if (!DemandedElts[i]) {   // If not demanded, set to undef.
973         Elts.push_back(Undef);
974         UndefElts.setBit(i);
975         continue;
976       }
977
978       Constant *Elt = C->getAggregateElement(i);
979       if (!Elt) return nullptr;
980
981       if (isa<UndefValue>(Elt)) {   // Already undef.
982         Elts.push_back(Undef);
983         UndefElts.setBit(i);
984       } else {                               // Otherwise, defined.
985         Elts.push_back(Elt);
986       }
987     }
988
989     // If we changed the constant, return it.
990     Constant *NewCV = ConstantVector::get(Elts);
991     return NewCV != C ? NewCV : nullptr;
992   }
993
994   // Limit search depth.
995   if (Depth == 10)
996     return nullptr;
997
998   // If multiple users are using the root value, proceed with
999   // simplification conservatively assuming that all elements
1000   // are needed.
1001   if (!V->hasOneUse()) {
1002     // Quit if we find multiple users of a non-root value though.
1003     // They'll be handled when it's their turn to be visited by
1004     // the main instcombine process.
1005     if (Depth != 0)
1006       // TODO: Just compute the UndefElts information recursively.
1007       return nullptr;
1008
1009     // Conservatively assume that all elements are needed.
1010     DemandedElts = EltMask;
1011   }
1012
1013   Instruction *I = dyn_cast<Instruction>(V);
1014   if (!I) return nullptr;        // Only analyze instructions.
1015
1016   bool MadeChange = false;
1017   APInt UndefElts2(VWidth, 0);
1018   Value *TmpV;
1019   switch (I->getOpcode()) {
1020   default: break;
1021
1022   case Instruction::InsertElement: {
1023     // If this is a variable index, we don't know which element it overwrites.
1024     // demand exactly the same input as we produce.
1025     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1026     if (!Idx) {
1027       // Note that we can't propagate undef elt info, because we don't know
1028       // which elt is getting updated.
1029       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1030                                         UndefElts2, Depth+1);
1031       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1032       break;
1033     }
1034
1035     // If this is inserting an element that isn't demanded, remove this
1036     // insertelement.
1037     unsigned IdxNo = Idx->getZExtValue();
1038     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1039       Worklist.Add(I);
1040       return I->getOperand(0);
1041     }
1042
1043     // Otherwise, the element inserted overwrites whatever was there, so the
1044     // input demanded set is simpler than the output set.
1045     APInt DemandedElts2 = DemandedElts;
1046     DemandedElts2.clearBit(IdxNo);
1047     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1048                                       UndefElts, Depth+1);
1049     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1050
1051     // The inserted element is defined.
1052     UndefElts.clearBit(IdxNo);
1053     break;
1054   }
1055   case Instruction::ShuffleVector: {
1056     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1057     uint64_t LHSVWidth =
1058       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1059     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1060     for (unsigned i = 0; i < VWidth; i++) {
1061       if (DemandedElts[i]) {
1062         unsigned MaskVal = Shuffle->getMaskValue(i);
1063         if (MaskVal != -1u) {
1064           assert(MaskVal < LHSVWidth * 2 &&
1065                  "shufflevector mask index out of range!");
1066           if (MaskVal < LHSVWidth)
1067             LeftDemanded.setBit(MaskVal);
1068           else
1069             RightDemanded.setBit(MaskVal - LHSVWidth);
1070         }
1071       }
1072     }
1073
1074     APInt UndefElts4(LHSVWidth, 0);
1075     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1076                                       UndefElts4, Depth+1);
1077     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1078
1079     APInt UndefElts3(LHSVWidth, 0);
1080     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1081                                       UndefElts3, Depth+1);
1082     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1083
1084     bool NewUndefElts = false;
1085     for (unsigned i = 0; i < VWidth; i++) {
1086       unsigned MaskVal = Shuffle->getMaskValue(i);
1087       if (MaskVal == -1u) {
1088         UndefElts.setBit(i);
1089       } else if (!DemandedElts[i]) {
1090         NewUndefElts = true;
1091         UndefElts.setBit(i);
1092       } else if (MaskVal < LHSVWidth) {
1093         if (UndefElts4[MaskVal]) {
1094           NewUndefElts = true;
1095           UndefElts.setBit(i);
1096         }
1097       } else {
1098         if (UndefElts3[MaskVal - LHSVWidth]) {
1099           NewUndefElts = true;
1100           UndefElts.setBit(i);
1101         }
1102       }
1103     }
1104
1105     if (NewUndefElts) {
1106       // Add additional discovered undefs.
1107       SmallVector<Constant*, 16> Elts;
1108       for (unsigned i = 0; i < VWidth; ++i) {
1109         if (UndefElts[i])
1110           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1111         else
1112           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1113                                           Shuffle->getMaskValue(i)));
1114       }
1115       I->setOperand(2, ConstantVector::get(Elts));
1116       MadeChange = true;
1117     }
1118     break;
1119   }
1120   case Instruction::Select: {
1121     APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
1122     if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
1123       for (unsigned i = 0; i < VWidth; i++) {
1124         if (CV->getAggregateElement(i)->isNullValue())
1125           LeftDemanded.clearBit(i);
1126         else
1127           RightDemanded.clearBit(i);
1128       }
1129     }
1130
1131     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded,
1132                                       UndefElts, Depth+1);
1133     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1134
1135     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
1136                                       UndefElts2, Depth+1);
1137     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
1138
1139     // Output elements are undefined if both are undefined.
1140     UndefElts &= UndefElts2;
1141     break;
1142   }
1143   case Instruction::BitCast: {
1144     // Vector->vector casts only.
1145     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1146     if (!VTy) break;
1147     unsigned InVWidth = VTy->getNumElements();
1148     APInt InputDemandedElts(InVWidth, 0);
1149     unsigned Ratio;
1150
1151     if (VWidth == InVWidth) {
1152       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1153       // elements as are demanded of us.
1154       Ratio = 1;
1155       InputDemandedElts = DemandedElts;
1156     } else if (VWidth > InVWidth) {
1157       // Untested so far.
1158       break;
1159
1160       // If there are more elements in the result than there are in the source,
1161       // then an input element is live if any of the corresponding output
1162       // elements are live.
1163       Ratio = VWidth/InVWidth;
1164       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1165         if (DemandedElts[OutIdx])
1166           InputDemandedElts.setBit(OutIdx/Ratio);
1167       }
1168     } else {
1169       // Untested so far.
1170       break;
1171
1172       // If there are more elements in the source than there are in the result,
1173       // then an input element is live if the corresponding output element is
1174       // live.
1175       Ratio = InVWidth/VWidth;
1176       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1177         if (DemandedElts[InIdx/Ratio])
1178           InputDemandedElts.setBit(InIdx);
1179     }
1180
1181     // div/rem demand all inputs, because they don't want divide by zero.
1182     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1183                                       UndefElts2, Depth+1);
1184     if (TmpV) {
1185       I->setOperand(0, TmpV);
1186       MadeChange = true;
1187     }
1188
1189     UndefElts = UndefElts2;
1190     if (VWidth > InVWidth) {
1191       llvm_unreachable("Unimp");
1192       // If there are more elements in the result than there are in the source,
1193       // then an output element is undef if the corresponding input element is
1194       // undef.
1195       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1196         if (UndefElts2[OutIdx/Ratio])
1197           UndefElts.setBit(OutIdx);
1198     } else if (VWidth < InVWidth) {
1199       llvm_unreachable("Unimp");
1200       // If there are more elements in the source than there are in the result,
1201       // then a result element is undef if all of the corresponding input
1202       // elements are undef.
1203       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1204       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1205         if (!UndefElts2[InIdx])            // Not undef?
1206           UndefElts.clearBit(InIdx/Ratio);    // Clear undef bit.
1207     }
1208     break;
1209   }
1210   case Instruction::And:
1211   case Instruction::Or:
1212   case Instruction::Xor:
1213   case Instruction::Add:
1214   case Instruction::Sub:
1215   case Instruction::Mul:
1216     // div/rem demand all inputs, because they don't want divide by zero.
1217     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1218                                       UndefElts, Depth+1);
1219     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1220     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1221                                       UndefElts2, Depth+1);
1222     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1223
1224     // Output elements are undefined if both are undefined.  Consider things
1225     // like undef&0.  The result is known zero, not undef.
1226     UndefElts &= UndefElts2;
1227     break;
1228   case Instruction::FPTrunc:
1229   case Instruction::FPExt:
1230     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1231                                       UndefElts, Depth+1);
1232     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1233     break;
1234
1235   case Instruction::Call: {
1236     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1237     if (!II) break;
1238     switch (II->getIntrinsicID()) {
1239     default: break;
1240
1241     // Binary vector operations that work column-wise.  A dest element is a
1242     // function of the corresponding input elements from the two inputs.
1243     case Intrinsic::x86_sse_sub_ss:
1244     case Intrinsic::x86_sse_mul_ss:
1245     case Intrinsic::x86_sse_min_ss:
1246     case Intrinsic::x86_sse_max_ss:
1247     case Intrinsic::x86_sse2_sub_sd:
1248     case Intrinsic::x86_sse2_mul_sd:
1249     case Intrinsic::x86_sse2_min_sd:
1250     case Intrinsic::x86_sse2_max_sd:
1251       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
1252                                         UndefElts, Depth+1);
1253       if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
1254       TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
1255                                         UndefElts2, Depth+1);
1256       if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
1257
1258       // If only the low elt is demanded and this is a scalarizable intrinsic,
1259       // scalarize it now.
1260       if (DemandedElts == 1) {
1261         switch (II->getIntrinsicID()) {
1262         default: break;
1263         case Intrinsic::x86_sse_sub_ss:
1264         case Intrinsic::x86_sse_mul_ss:
1265         case Intrinsic::x86_sse2_sub_sd:
1266         case Intrinsic::x86_sse2_mul_sd:
1267           // TODO: Lower MIN/MAX/ABS/etc
1268           Value *LHS = II->getArgOperand(0);
1269           Value *RHS = II->getArgOperand(1);
1270           // Extract the element as scalars.
1271           LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
1272             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1273           RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
1274             ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1275
1276           switch (II->getIntrinsicID()) {
1277           default: llvm_unreachable("Case stmts out of sync!");
1278           case Intrinsic::x86_sse_sub_ss:
1279           case Intrinsic::x86_sse2_sub_sd:
1280             TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
1281                                                         II->getName()), *II);
1282             break;
1283           case Intrinsic::x86_sse_mul_ss:
1284           case Intrinsic::x86_sse2_mul_sd:
1285             TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
1286                                                          II->getName()), *II);
1287             break;
1288           }
1289
1290           Instruction *New =
1291             InsertElementInst::Create(
1292               UndefValue::get(II->getType()), TmpV,
1293               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1294                                       II->getName());
1295           InsertNewInstWith(New, *II);
1296           return New;
1297         }
1298       }
1299
1300       // Output elements are undefined if both are undefined.  Consider things
1301       // like undef&0.  The result is known zero, not undef.
1302       UndefElts &= UndefElts2;
1303       break;
1304     }
1305     break;
1306   }
1307   }
1308   return MadeChange ? I : nullptr;
1309 }