InstCombine: Move Sub->Xor rule from SimplifyDemanded to InstCombine
[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 "InstCombineInternal.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
18
19 using namespace llvm;
20 using namespace llvm::PatternMatch;
21
22 #define DEBUG_TYPE "instcombine"
23
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,
29                                    APInt Demanded) {
30   assert(I && "No instruction?");
31   assert(OpNo < I->getNumOperands() && "Operand index too large");
32
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;
36
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)
40     return false;
41
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));
45
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);
55       }
56     }
57   }
58
59   return true;
60 }
61
62
63
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));
71
72   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, KnownZero, KnownOne,
73                                      0, &Inst);
74   if (!V) return false;
75   if (V == &Inst) return true;
76   ReplaceInstUsesWith(Inst, V);
77   return true;
78 }
79
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,
85                                         unsigned Depth) {
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;
90   U = NewVal;
91   return true;
92 }
93
94
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.
110 ///
111 /// This returns null if it did not change anything and it permits no
112 /// simplification.  This returns V itself if it did some simplification of V's
113 /// operands based on the information about what bits are demanded. This returns
114 /// some other non-null value if it found out that V is equal to another value
115 /// in the context where the specified bits are demanded, but not for all users.
116 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
117                                              APInt &KnownZero, APInt &KnownOne,
118                                              unsigned Depth,
119                                              Instruction *CxtI) {
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();
124   assert(
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;
134     return nullptr;
135   }
136   if (isa<ConstantPointerNull>(V)) {
137     // We know all of the bits for a constant!
138     KnownOne.clearAllBits();
139     KnownZero = DemandedMask;
140     return nullptr;
141   }
142
143   KnownZero.clearAllBits();
144   KnownOne.clearAllBits();
145   if (DemandedMask == 0) {   // Not demanding any bits from V.
146     if (isa<UndefValue>(V))
147       return nullptr;
148     return UndefValue::get(VTy);
149   }
150
151   if (Depth == 6)        // Limit search depth.
152     return nullptr;
153
154   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
155   APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
156
157   Instruction *I = dyn_cast<Instruction>(V);
158   if (!I) {
159     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
160     return nullptr;        // Only analyze instructions.
161   }
162
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,
174                        CxtI);
175       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
176                        CxtI);
177
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
180       // context.
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);
187
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);
191
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.
195
196       // If either the LHS or the RHS are One, the result is One.
197       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
198                        CxtI);
199       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
200                        CxtI);
201
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
204       // context.
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);
211
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.
223
224       computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth + 1,
225                        CxtI);
226       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
227                        CxtI);
228
229       // If all of the demanded bits are known zero on one side, return the
230       // other.
231       if ((DemandedMask & RHSKnownZero) == DemandedMask)
232         return I->getOperand(0);
233       if ((DemandedMask & LHSKnownZero) == DemandedMask)
234         return I->getOperand(1);
235     }
236
237     // Compute the KnownZero/KnownOne bits to simplify things downstream.
238     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
239     return nullptr;
240   }
241
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);
248
249   switch (I->getOpcode()) {
250   default:
251     computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
252     break;
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))
259       return I;
260     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
261     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
262
263     // If the client is only demanding bits that we know, return the known
264     // constant.
265     if ((DemandedMask & ((RHSKnownZero | LHSKnownZero)|
266                          (RHSKnownOne & LHSKnownOne))) == DemandedMask)
267       return Constant::getIntegerValue(VTy, RHSKnownOne & LHSKnownOne);
268
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);
277
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);
281
282     // If the RHS is a constant, see if we can simplify it.
283     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
284       return I;
285
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;
290     break;
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))
297       return I;
298     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
299     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
300
301     // If the client is only demanding bits that we know, return the known
302     // constant.
303     if ((DemandedMask & ((RHSKnownZero & LHSKnownZero)|
304                          (RHSKnownOne | LHSKnownOne))) == DemandedMask)
305       return Constant::getIntegerValue(VTy, RHSKnownOne | LHSKnownOne);
306
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);
315
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);
324
325     // If the RHS is a constant, see if we can simplify it.
326     if (ShrinkDemandedConstant(I, 1, DemandedMask))
327       return I;
328
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;
333     break;
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))
339       return I;
340     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
341     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
342
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);
349
350     // If the client is only demanding bits that we know, return the known
351     // constant.
352     if ((DemandedMask & (IKnownZero|IKnownOne)) == DemandedMask)
353       return Constant::getIntegerValue(VTy, IKnownOne);
354
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);
361
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) {
366       Instruction *Or =
367         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
368                                  I->getName());
369       return InsertNewInstWith(Or, *I);
370     }
371
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) {
377       // all known
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);
383       }
384     }
385
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))
389       return I;
390
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);
403
404         Constant *AndC =
405           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
406         Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
407         InsertNewInstWith(NewAnd, *I);
408
409         Constant *XorC =
410           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
411         Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
412         return InsertNewInstWith(NewXor, *I);
413       }
414
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);
419     break;
420   }
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))
426       return I;
427     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
428     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
429
430     // If the operands are constants, see if we can simplify them.
431     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
432         ShrinkDemandedConstant(I, 2, DemandedMask))
433       return I;
434
435     // Only known if known in both the LHS and RHS.
436     KnownOne = RHSKnownOne & LHSKnownOne;
437     KnownZero = RHSKnownZero & LHSKnownZero;
438     break;
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))
446       return I;
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?");
451     break;
452   }
453   case Instruction::BitCast:
454     if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
455       return nullptr;  // vector->int or fp->int?
456
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.
462           return nullptr;
463       } else
464         // Don't touch a scalar-to-vector bitcast.
465         return nullptr;
466     } else if (I->getOperand(0)->getType()->isVectorTy())
467       // Don't touch a vector-to-scalar bitcast.
468       return nullptr;
469
470     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, KnownZero,
471                              KnownOne, Depth + 1))
472       return I;
473     assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
474     break;
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();
478
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))
484       return I;
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);
491     break;
492   }
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();
496
497     APInt InputDemandedBits = DemandedMask &
498                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
499
500     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
501     // If any of the sign extended bits are demanded, we know that the sign
502     // bit is demanded.
503     if ((NewBits & DemandedMask) != 0)
504       InputDemandedBits.setBit(SrcBitWidth-1);
505
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))
511       return I;
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?");
516
517     // If the sign bit of the input is known set or clear, then we know the
518     // top bits of the result.
519
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
527       KnownOne |= NewBits;
528     }
529     break;
530   }
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
534     // either.
535     unsigned NLZ = DemandedMask.countLeadingZeros();
536
537     // If there is a constant on the RHS, there are a variety of xformations
538     // we can do.
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.
542       if (RHS->isZero())
543         break;
544
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));
548
549       // Find information about known zero/one bits in the input.
550       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
551                                LHSKnownZero, LHSKnownOne, Depth + 1))
552         return I;
553
554       // If the RHS of the add has bits set that can't affect the input, reduce
555       // the constant.
556       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
557         return I;
558
559       // Avoid excess work.
560       if (LHSKnownZero == 0 && LHSKnownOne == 0)
561         break;
562
563       // Turn it into OR if input bits are zero.
564       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
565         Instruction *Or =
566           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
567                                    I->getName());
568         return InsertNewInstWith(Or, *I);
569       }
570
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.
576
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
579       // this scan.
580       const APInt &RHSVal = RHS->getValue();
581       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
582
583       // Now that we know which bits have carries, compute the known-1/0 sets.
584
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;
589
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;
593     } else {
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);
606           return I;
607         }
608       }
609     }
610     break;
611   }
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);
626         return I;
627       }
628     }
629
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);
633     break;
634   case Instruction::Shl:
635     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
636       {
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);
642           if (R)
643             return R;
644         }
645       }
646
647       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
648       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
649
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);
656
657       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
658                                KnownOne, Depth + 1))
659         return I;
660       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
661       KnownZero <<= ShiftAmt;
662       KnownOne  <<= ShiftAmt;
663       // low bits known zero.
664       if (ShiftAmt)
665         KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
666     }
667     break;
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);
672
673       // Unsigned shift right.
674       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
675
676       // If the shift is exact, then it does demand the low bits (and knows that
677       // they are zero).
678       if (cast<LShrOperator>(I)->isExact())
679         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
680
681       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
682                                KnownOne, Depth + 1))
683         return I;
684       assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
685       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
686       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
687       if (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.
691       }
692     }
693     break;
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);
704     }
705
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);
710
711     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
712       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
713
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
717       // demanded.
718       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
719         DemandedMaskIn.setBit(BitWidth-1);
720
721       // If the shift is exact, then it does demand the low bits (and knows that
722       // they are zero).
723       if (cast<AShrOperator>(I)->isExact())
724         DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
725
726       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, KnownZero,
727                                KnownOne, Depth + 1))
728         return I;
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);
734
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);
739
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),
746                                                             SA, I->getName());
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;
751       }
752     }
753     break;
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())
759         break;
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);
764
765         APInt LowBits = RA - 1;
766         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
767         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2, LHSKnownZero,
768                                  LHSKnownOne, Depth + 1))
769           return I;
770
771         // The low bits of LHS are unchanged by the srem.
772         KnownZero = LHSKnownZero & LowBits;
773         KnownOne = LHSKnownOne & LowBits;
774
775         // If LHS is non-negative or has all low bits zero, then the upper bits
776         // are all zero.
777         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
778           KnownZero |= ~LowBits;
779
780         // If LHS is negative and not all low bits are zero, then the upper bits
781         // are all one.
782         if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
783           KnownOne |= ~LowBits;
784
785         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
786       }
787     }
788
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,
794                        CxtI);
795       // If it's known zero, our sign bit is also zero.
796       if (LHSKnownZero.isNegative())
797         KnownZero.setBit(KnownZero.getBitWidth() - 1);
798     }
799     break;
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))
807       return I;
808
809     unsigned Leaders = KnownZero2.countLeadingOnes();
810     Leaders = std::max(Leaders,
811                        KnownZero2.countLeadingOnes());
812     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
813     break;
814   }
815   case Instruction::Call:
816     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
817       switch (II->getIntrinsicID()) {
818       default: break;
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();
824
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.
828         NLZ &= ~7;
829         NTZ &= ~7;
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;
834
835           // Replace this with either a left or right shift to get the byte into
836           // the right place.
837           Instruction *NewVal;
838           if (InputBit > ResultBit)
839             NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
840                     ConstantInt::get(I->getType(), InputBit-ResultBit));
841           else
842             NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
843                     ConstantInt::get(I->getType(), ResultBit-InputBit));
844           NewVal->takeName(I);
845           return InsertNewInstWith(NewVal, *I);
846         }
847
848         // TODO: Could compute known zero/one bits based on the input.
849         break;
850       }
851       case Intrinsic::x86_sse42_crc32_64_64:
852         KnownZero = APInt::getHighBitsSet(64, 32);
853         return nullptr;
854       }
855     }
856     computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
857     break;
858   }
859
860   // If the client is only demanding bits that we know, return the known
861   // constant.
862   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
863     return Constant::getIntegerValue(VTy, KnownOne);
864   return nullptr;
865 }
866
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
870 /// of "C2-C1".
871 ///
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
878 ///     rest bits.
879 ///
880 /// Currently we only test condition 2).
881 ///
882 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
883 /// not successful.
884 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
885   Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
886
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.
891
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.
897
898   unsigned ShlAmt = ShlOp1.getZExtValue();
899   unsigned ShrAmt = ShrOp1.getZExtValue();
900
901   KnownOne.clearAllBits();
902   KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
903   KnownZero &= DemandedMask;
904
905   APInt BitMask1(APInt::getAllOnesValue(BitWidth));
906   APInt BitMask2(APInt::getAllOnesValue(BitWidth));
907
908   bool isLshr = (Shr->getOpcode() == Instruction::LShr);
909   BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
910                       (BitMask1.ashr(ShrAmt) << ShlAmt);
911
912   if (ShrAmt <= ShlAmt) {
913     BitMask2 <<= (ShlAmt - ShrAmt);
914   } else {
915     BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
916                         BitMask2.ashr(ShrAmt - ShlAmt);
917   }
918
919   // Check if condition-2 (see the comment to this function) is satified.
920   if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
921     if (ShrAmt == ShlAmt)
922       return VarX;
923
924     if (!Shr->hasOneUse())
925       return nullptr;
926
927     BinaryOperator *New;
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());
934     } else {
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);
940     }
941
942     return InsertNewInstWith(New, *Shl);
943   }
944
945   return nullptr;
946 }
947
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.
952 ///
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,
957                                                 APInt &UndefElts,
958                                                 unsigned Depth) {
959   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
960   APInt EltMask(APInt::getAllOnesValue(VWidth));
961   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
962
963   if (isa<UndefValue>(V)) {
964     // If the entire vector is undefined, just return this info.
965     UndefElts = EltMask;
966     return nullptr;
967   }
968
969   if (DemandedElts == 0) { // If nothing is demanded, provide undef.
970     UndefElts = EltMask;
971     return UndefValue::get(V->getType());
972   }
973
974   UndefElts = 0;
975
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
979     // anything.
980     if (DemandedElts.isAllOnesValue())
981       return nullptr;
982
983     Type *EltTy = cast<VectorType>(V->getType())->getElementType();
984     Constant *Undef = UndefValue::get(EltTy);
985
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);
990         UndefElts.setBit(i);
991         continue;
992       }
993
994       Constant *Elt = C->getAggregateElement(i);
995       if (!Elt) return nullptr;
996
997       if (isa<UndefValue>(Elt)) {   // Already undef.
998         Elts.push_back(Undef);
999         UndefElts.setBit(i);
1000       } else {                               // Otherwise, defined.
1001         Elts.push_back(Elt);
1002       }
1003     }
1004
1005     // If we changed the constant, return it.
1006     Constant *NewCV = ConstantVector::get(Elts);
1007     return NewCV != C ? NewCV : nullptr;
1008   }
1009
1010   // Limit search depth.
1011   if (Depth == 10)
1012     return nullptr;
1013
1014   // If multiple users are using the root value, proceed with
1015   // simplification conservatively assuming that all elements
1016   // are needed.
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.
1021     if (Depth != 0)
1022       // TODO: Just compute the UndefElts information recursively.
1023       return nullptr;
1024
1025     // Conservatively assume that all elements are needed.
1026     DemandedElts = EltMask;
1027   }
1028
1029   Instruction *I = dyn_cast<Instruction>(V);
1030   if (!I) return nullptr;        // Only analyze instructions.
1031
1032   bool MadeChange = false;
1033   APInt UndefElts2(VWidth, 0);
1034   Value *TmpV;
1035   switch (I->getOpcode()) {
1036   default: break;
1037
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));
1042     if (!Idx) {
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; }
1048       break;
1049     }
1050
1051     // If this is inserting an element that isn't demanded, remove this
1052     // insertelement.
1053     unsigned IdxNo = Idx->getZExtValue();
1054     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1055       Worklist.Add(I);
1056       return I->getOperand(0);
1057     }
1058
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; }
1066
1067     // The inserted element is defined.
1068     UndefElts.clearBit(IdxNo);
1069     break;
1070   }
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);
1084           else
1085             RightDemanded.setBit(MaskVal - LHSVWidth);
1086         }
1087       }
1088     }
1089
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; }
1094
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; }
1099
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);
1112         }
1113       } else {
1114         if (UndefElts3[MaskVal - LHSVWidth]) {
1115           NewUndefElts = true;
1116           UndefElts.setBit(i);
1117         }
1118       }
1119     }
1120
1121     if (NewUndefElts) {
1122       // Add additional discovered undefs.
1123       SmallVector<Constant*, 16> Elts;
1124       for (unsigned i = 0; i < VWidth; ++i) {
1125         if (UndefElts[i])
1126           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1127         else
1128           Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1129                                           Shuffle->getMaskValue(i)));
1130       }
1131       I->setOperand(2, ConstantVector::get(Elts));
1132       MadeChange = true;
1133     }
1134     break;
1135   }
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);
1142         else
1143           RightDemanded.clearBit(i);
1144       }
1145     }
1146
1147     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded, UndefElts,
1148                                       Depth + 1);
1149     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1150
1151     TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
1152                                       UndefElts2, Depth + 1);
1153     if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
1154
1155     // Output elements are undefined if both are undefined.
1156     UndefElts &= UndefElts2;
1157     break;
1158   }
1159   case Instruction::BitCast: {
1160     // Vector->vector casts only.
1161     VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1162     if (!VTy) break;
1163     unsigned InVWidth = VTy->getNumElements();
1164     APInt InputDemandedElts(InVWidth, 0);
1165     unsigned Ratio;
1166
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.
1170       Ratio = 1;
1171       InputDemandedElts = DemandedElts;
1172     } else if (VWidth > InVWidth) {
1173       // Untested so far.
1174       break;
1175
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);
1183       }
1184     } else {
1185       // Untested so far.
1186       break;
1187
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
1190       // live.
1191       Ratio = InVWidth/VWidth;
1192       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1193         if (DemandedElts[InIdx/Ratio])
1194           InputDemandedElts.setBit(InIdx);
1195     }
1196
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);
1200     if (TmpV) {
1201       I->setOperand(0, TmpV);
1202       MadeChange = true;
1203     }
1204
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
1210       // undef.
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.
1223     }
1224     break;
1225   }
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,
1234                                       Depth + 1);
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; }
1239
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;
1243     break;
1244   case Instruction::FPTrunc:
1245   case Instruction::FPExt:
1246     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, UndefElts,
1247                                       Depth + 1);
1248     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1249     break;
1250
1251   case Instruction::Call: {
1252     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1253     if (!II) break;
1254     switch (II->getIntrinsicID()) {
1255     default: break;
1256
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; }
1273
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()) {
1278         default: break;
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);
1291
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);
1298             break;
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);
1303             break;
1304           }
1305
1306           Instruction *New =
1307             InsertElementInst::Create(
1308               UndefValue::get(II->getType()), TmpV,
1309               ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1310                                       II->getName());
1311           InsertNewInstWith(New, *II);
1312           return New;
1313         }
1314       }
1315
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;
1319       break;
1320     }
1321     break;
1322   }
1323   }
1324   return MadeChange ? I : nullptr;
1325 }