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