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